[英]i am trying to bind array value a prepared statement in php pdo but only the first element of the array that is bind
我想顯示一個時間表,下面是我懷疑錯誤所在的代碼片段。 其中的錯誤是綁定僅使用我命名為 class 的數組的第一個元素,盡管 class 數組中有兩個元素。 請誰能幫我弄清楚我哪里出錯了?
while($classes = $stmt->fetch(PDO::FETCH_ASSOC)){
$showtimetable.= "{\"class\":\"";
$showtimetable.= $classes["Form"].$classes["Label"];
$showtimetable.= "\",\"subjects\":[";
//iterate every class in different times to check if they are having a session in the timetable
foreach($time as $times){
$selectlessonquery="SELECT `staffnumber`, `subject` FROM `".$timetablename."` WHERE
`Form`=? AND `Label`=? AND daytime=?";
try{
//this variable contain the array of variable classes
echo $classes["Form"].$classes["Label"];
//this works fine with output of classes as 1E and IN
//on adding these code that will use the value in $classes only 1E it binding
in prepared statement
$stmt=$conn->prepare($selectlessonquery);
$stmt->bindParam(1,$classes["Form"]);
$stmt->bindParam(2,$classes["Label"]);
$stmt->bindParam(3,$times);
$stmt->execute();
while($subject = $stmt->fetch(PDO::FETCH_ASSOC)){
if(!$subject){
//if no matching row then make the value to be empty string
$showtimetable.= "{\"subject\":\"";
$showtimetable.= " \"";
$showtimetable.= " "."},";
}else{
$showtimetable.= "{\"subject\":\"";
$showtimetable.= $subject["subject"]." ";
$showtimetable.= $subject["staffnumber"]."\"},";
}
}
}catch(Exception $e){
echo "error Ocuured ". $e->getMessage();
}
}
$showtimetable=rtrim($showtimetable,",");
$showtimetable.="]";
$showtimetable.="},";
}
echo $showtimetable
//the output contains on data relevant to 1E and it isnt looping to the other value as expected
你必須這樣做。 因為第二個參數必須在bindParam()
通過引用傳遞。
$table = 'users';
$sql = "INSERT INTO `{$table}` (username, password, name, age) VALUES(?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->bindParam(3, $name);
$stmt->bindParam(4, $age);
$username = 'zill';
$password = '12345';
$name = 'zilanicse';
$age = 31;
// Executes the query
$stmt->execute();
問題是 if 在一段時間內的定位導致代碼意外停止,即使它旨在在沒有獲取行的情況下為主題提供默認值。 正確的方法是
foreach($time as $times){
$selectlessonquery="SELECT `staffnumber`, `subject` FROM `".$timetablename."`
WHERE `Form`=? AND `Label`=? AND daytime=?";
try{
//this variable contain the array of variable classes
$subjects=$conn->prepare($selectlessonquery);
$subjects->bindParam(1,$classes["Form"]);
$subjects->bindParam(2,$classes["Label"]);
$subjects->bindParam(3,$times);
$subjects->execute();
if($subjects->rowCount()==0){
$showtimetable.= "{\"subject\":\"";
$showtimetable.= " \"";
$showtimetable.= " "."},";
}else{
while($subject=$subjects->fetch(PDO::FETCH_ASSOC)){
$showtimetable.= "{\"subject\":\"";
$showtimetable.= $subject["subject"]." ";
$showtimetable.= $subject["staffnumber"]."\"},";
}
}
}catch(Exception $e){
echo "error Ocuured ". $e->getMessage();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.