uneeb meer uneeb meer - 4 months ago 9
SQL Question

using variable inside php query

hi i want to use different tables in from clause sql query every time in a loop issue is it is not accepting my code here is the code

$tbl0="atom_supplier_oe";
$tbl1="atom_supplier_silver_coated_slotted_and_crossed_drilled";
$tbl2="atom_supplier_black_coated_slotted_and_crossed_drilled";
$tbl3="atom_supplier_just_crossed_drilled";
$tbl4="atom_supplier_just_slotted";
$tbl5="atom_supplier_slotted_and_crossed_drilled";

for($i=0;$i<6;$i++){
$sql="select * from $tbl'+$i' where client_id='$id'";
if(!$result=mysqli_query($db,$sql)){

echo mysql_error($db);
}

$count=mysqli_num_rows($result);

if($count==0){
break;
//echo mysqli_error($db);
}


what is the issue ? i want to use different table for every iteration for comparison.thanks in advance

Answer

Try using something like this. Table names in an array, foreach over that array and process the results accordingly.

$id = '';   // not sure where you are getting this from
$db = '';   // again this was not in your example above

$tables = [
    "atom_supplier_oe",
    "atom_supplier_silver_coated_slotted_and_crossed_drilled",
    "atom_supplier_black_coated_slotted_and_crossed_drilled",
    "atom_supplier_just_crossed_drilled",
    "atom_supplier_just_slotted",
    "atom_supplier_slotted_and_crossed_drilled",
];
foreach ($tables as $table) {
    $sql = sprintf("SELECT * FROM `%s` WHERE client_id = %d", $table, $id);

    if (!$result=mysqli_query($db,$sql)) {
        echo mysql_error($db);
        continue;
        // or break if you want to still check the other tables.
    }

    // do something with the result here ($result)
}
Comments