我想通过检查两个条件来更新seat_status
。
第一个条件= bus_id
第二个条件= seat_title
我在函数cancelbook
中使用此代码。
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
for($i=0;$i<count($seat_no);$i++)
{
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active' WHERE bus_id=:bus_id AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat_no[$i]);
}
if ($stmtactive->execute()) {
exit();
return true;
}
return false;
}
我得到这个错误 注意:数组到字符串转换
答案 0 :(得分:1)
执行循环的方式只会更新一行,以更新每次迭代时应执行语句的每一行。
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
foreach($seat_no as $seat) {
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat['seat_no']);
$stmtactive->execute();
}
}
答案 1 :(得分:0)
似乎$seat_no[$i]
不是字符串而且它是一个数组,(我之前建议它var_dump($seat_no[$i]);
),我的问题是它应该是以下代码段:
使用
$stmtactive->bindParam('seat_title',$seat_no[$i]['seat_no']);
而不是
$stmtactive->bindParam('seat_title',$seat_no[$i]);
代码中的将解决您的问题。
当然,最好不要使用 来学习使用 foreach
但另一个性能更佳的解决方案是只使用一次更新而不是几次更新!!!
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
$seat_numbers = array_values($seat_no);
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title IN (:seat_title"));
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',implode(",",$seat_numbers));
$stmtactive->execute();
}
此外,请删除代码中的退出,这是代码中的错误