使用for循环将值添加到MySQL插入查询

时间:2014-12-24 09:58:01

标签: php mysql

PHP:

$bookquery = "SELECT * FROM heli_book ORDER BY book_id DESC LIMIT 1";
$bookget = mysql_query("$bookquery");
$booking = mysql_fetch_assoc($bookget, MYSQL_ASSOC);

$custquery = "SELECT cust_id FROM heli_cust LIMIT ".$total."";
$custget = mysql_query("$custquery");
$cust = mysql_fetch_assoc($custget, MYSQL_ASSOC);

$bcusquery = "INSERT INTO heli_bcus (bcus_book, bcus_cust) VALUES ";

for($x = 0; $x < count($cust_fname); $x++) {
    $bcusquery .= "('".$bookid."', '".$custid."')";
    if ($x+1 != $total) {
        $bcusquery .= ", ";
    }
} 

        echo "<br>";
        echo $bcusquery;

我试图通过数组获得$custid seqence,但它一直是数组中的第一项。

当前结果: ('01','A'),('01','A'),('01','A')

期望的结果:
('01','A'),('01','B'),('01','C')

$totalcount(array_filter($cust_fname))的价值 $cust_fname = array_filter($_POST[cust_fname]);

1 个答案:

答案 0 :(得分:0)

搞定了!

要执行此操作 - 将$booking = mysql_fetch_assoc($bookget, MYSQL_ASSOC);移至for循环!

<强> 即:

        $bookquery = "SELECT * FROM heli_book ORDER BY book_id DESC LIMIT 1";
        $bookget = mysql_query("$bookquery");
        $booking = mysql_fetch_assoc($bookget, MYSQL_ASSOC);

        $custquery = "SELECT cust_id FROM heli_cust LIMIT ".$total."";
        $custget = mysql_query("$custquery");


        $bcusquery = "INSERT INTO heli_bcus (bcus_book, bcus_cust) VALUES ";

        $custid = $cust[cust_id];
        $bookid = $booking[book_id];

for($x = 0; $x < count($cust_fname); $x++) {
    $cust = mysql_fetch_assoc($custget, MYSQL_ASSOC);
    $bcusquery .= "('".$bookid."', '".$cust[cust_id]."')";
    if ($x+1 != $total) {
        $bcusquery .= ", ";
    }
} 

        echo "<br>";
        echo $bcusquery;