คำตอบที่ได้รับเลือกจากเจ้าของกระทู้
ความคิดเห็นที่ 4
Q : สมมติว่า มีข้อมูล 2 ข้อมูลที่ต้อง update แต่ว่า มันทำแค่รอบเดียว แล้วก็จบเลย มันไม่วน while ต่อ
$comm=" SELECT * FROM `order_detail`";
$comm.=" WHERE `order_id` = ".$_POST['order_id']; //รับค่ามาจาก POST เช็คแล้วมีค่า
$query = mysql_query($comm);
while($result = mysql_fetch_array($query))
{
$comm =" SELECT * FROM product";
$comm.=" WHERE product_id = ".$result['product_id'];
$queryPd = mysql_query($comm);
$resultPd = mysql_fetch_assoc($queryPd);
$amount = $resultPd['amount'];
$qty = $result['qty'];
$total = $qty + $amount;
//ส่วน update
$comm2= " UPDATE product SET ";
$comm2.=" amount = '".$total."'";
$comm2.=" WHERE product_id =".$result['product_id'];
$query2 = mysql_query($comm2); //<--- คือตรงนี้ครับ กรณี query ด้วย UPDATE มัน return true/false ครับ
// กรณีจะ query ซ้อนกันระวังตัวแปรครับ ลูปวงนอกตัวแปร $query เก็บค่าที่ return มาเป็น #resource สำหรับ fetch ครับ พอลูปด้านใน จขกท เอาตัวแปรเดิมไปรับค่าทำให้ $query มันเปลี่ยนไปเป็น true/false ครับ
// fetch เลย error เพราะ fetch ได้เฉพาะข้อมูลที่เป็น #resouce
if (!$query2)
{
//..
}
}
$comm=" SELECT * FROM `order_detail`";
$comm.=" WHERE `order_id` = ".$_POST['order_id']; //รับค่ามาจาก POST เช็คแล้วมีค่า
$query = mysql_query($comm);
while($result = mysql_fetch_array($query))
{
$comm =" SELECT * FROM product";
$comm.=" WHERE product_id = ".$result['product_id'];
$queryPd = mysql_query($comm);
$resultPd = mysql_fetch_assoc($queryPd);
$amount = $resultPd['amount'];
$qty = $result['qty'];
$total = $qty + $amount;
//ส่วน update
$comm2= " UPDATE product SET ";
$comm2.=" amount = '".$total."'";
$comm2.=" WHERE product_id =".$result['product_id'];
$query2 = mysql_query($comm2); //<--- คือตรงนี้ครับ กรณี query ด้วย UPDATE มัน return true/false ครับ
// กรณีจะ query ซ้อนกันระวังตัวแปรครับ ลูปวงนอกตัวแปร $query เก็บค่าที่ return มาเป็น #resource สำหรับ fetch ครับ พอลูปด้านใน จขกท เอาตัวแปรเดิมไปรับค่าทำให้ $query มันเปลี่ยนไปเป็น true/false ครับ
// fetch เลย error เพราะ fetch ได้เฉพาะข้อมูลที่เป็น #resouce
if (!$query2)
{
//..
}
}
แสดงความคิดเห็น
Error mysql_fetch_array() ช่วยดูให้หน่อย
ปล. ถ้าเอาส่วน update ออก ก็จะไม่ error ครับ มันทำอย่างไรได้บ้างครับ ?
$comm=" SELECT * FROM `order_detail`";
$comm.=" WHERE `order_id` = ".$_POST['order_id']; //รับค่ามาจาก POST เช็คแล้วมีค่า
$query = mysql_query($comm);
while($result = mysql_fetch_array($query)){
$comm =" SELECT * FROM product";
$comm.=" WHERE product_id = ".$result['product_id'];
$queryPd = mysql_query($comm);
$resultPd = mysql_fetch_assoc($queryPd);
$amount = $resultPd['amount'];
$qty = $result['qty'];
$total = $qty + $amount;
//ส่วน update
$comm= " UPDATE product SET ";
$comm.=" amount = '".$total."'";
$comm.=" WHERE product_id =".$result['product_id'];
$query = mysql_query($comm);
if (!$query) {
//..
}
}