在php查询中使用变量

时间:2016-07-21 11:15:17

标签: php mysql

嗨我想在每个循环问题中使用from子句sql查询中的不同表是不接受我的代码这里是代码

$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);
}

问题是什么?我想为每次迭代使用不同的表进行比较。提前谢谢

4 个答案:

答案 0 :(得分:0)

我希望对你有所帮助。

$tbl=array();
$tbl[]="atom_supplier_oe";
$tbl[]="atom_supplier_silver_coated_slotted_and_crossed_drilled";
$tbl[]="atom_supplier_black_coated_slotted_and_crossed_drilled";
$tbl[]="atom_supplier_just_crossed_drilled";
$tbl[]="atom_supplier_just_slotted";
$tbl[]="atom_supplier_slotted_and_crossed_drilled";

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

    echo mysqli_error($db);
}

$count=mysqli_num_rows($result);

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

答案 1 :(得分:0)

在循环中更改以下查询。

$sql="select * from ".${'tbl'.$i}." where client_id='$id'";

这可能会对你有帮助。

如果您有任何疑问,请与我们联系。

答案 2 :(得分:0)

尝试使用类似的东西。数组中的表名,foreach在该数组上并相应地处理结果。

$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)
}

答案 3 :(得分:-1)

&#34;选择*来自$ tbl&#34;。&#39; $ i&#39;。&#34;其中client_id =&#39; $ id&#39;&#34;

使用点运算符连接

相关问题