2014-12-24 81 views
0

PHP:使用循環將值添加到MySQL插入查詢

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

+0

因此,我們期望的結果。目前的結果是什麼? –

+1

只是一個側面說明,在別人射擊之前:不應該使用mysql_ *原型,因爲它已被棄用(從相當長一段時間),您應該使用mysqli_ *或PDO來代替,而不管您正在查詢的類型。 – briosheje

+0

editted above @u_mulder –

回答

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;