WHERE Clause with Array PHP-MYSQL

1

I have the following code, but it is not working and I can not find the error. I need to display the 3 lines (123), which are found in $fetch['list_carac'] .

<?php
include 'conect.php';

$sql = "SELECT list_carac FROM select_carac WHERE id_produto = 1";
$exec = $con->query( $sql ) or exit( $con->error );
$fetch = mysqli_fetch_assoc($exec); 
$fetch = str_replace( ",", "", $fetch);

echo($fetch['list_carac']);//aqui a saída é 123

foreach($fetch as $value){

$sql =  "SELECT nome_carac FROM carac WHERE id_carac = $value";

$exec = $con->query( $sql ) or exit( $con->error );

$row = mysqli_fetch_assoc($exec);

echo $row["nome_carac"];
}
?>

If I take out foreach and add id manually it returns the record that is in the nome_carac field. Otherwise it does not give error, but only shows the 1st output echo($fetch['list_carac']);//aqui a saída é 123 .

    
asked by anonymous 06.07.2016 / 23:54

1 answer

2

If you are sure that the DB is always comma, this is enough:

$sql = 'SELECT nome_carac FROM carac WHERE id_carac IN ('.$lista.')';

Applied to your code:

<?php
    include 'conect.php';

    $sql = 'SELECT list_carac FROM select_carac WHERE id_produto = 1';
    $exec = $con->query( $sql ) or die( $con->error );
    $fetch = mysqli_fetch_assoc($exec); 

    $lista = mysqli_real_escape_string( $con, $fetch['list_carac'] );
    $sql = 'SELECT nome_carac FROM carac WHERE id_carac IN ( '.$lista.')';
    $exec = $con->query( $sql ) or exit( $con->error );

    while( $row = mysqli_fetch_assoc($exec) ){ 
       echo $row["nome_carac"];
    }
?>

Eventually, if the list is not just numeric, you need a little sanitization (with quotation marks):

    $caracteres = explode( ',', $fetch['list_carac'] );
    foreach( $caracteres as $caractere ) {
        $lista .= "'".mysqli_real_escape_string( $con, $caractere )."',";
    }
    $lista = rtrim( $lista, "," );
    
06.07.2016 / 23:58