我试图从表“totals”中提取所有“totalsDate”值,然后插入一条新记录或根据变量 $date 更新现有记录。
//getting all the dates from the totals table and assigning to row
$sqlDate = "SELECT totalsDate FROM totals";
$query = mysqli_query($dbCon, $sqlDate);
//$row = mysqli_fetch_array($query);
while($row = mysqli_fetch_array($query)){
$rowDate = $row['totalsDate'];
//if statement to either update the totals table or create a new record
if($rowDate = $date){
$sqlThree = "UPDATE totals SET lodgements = '$lodgementsAfter' WHERE branch_name = '$branchTest' AND totalsDate = '$date'";
$query = mysqli_query($dbCon, $sqlThree);
}
else {
$sqlFour = "INSERT INTO totals VALUES(NULL, '$branchTest', 0, '$amount', 0, '$date')";
$query = mysqli_query($dbCon, $sqlFour);
}
}
更新部分有效,但是我的 else 语句永远不会被执行,并且无法输入新记录。我也收到此错误:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
我对使用 mysqli_fetch_array 以及如何实际使用数据有点困惑?
感谢您的帮助。
最佳答案
问题之一是 $query
在循环内被覆盖;参见这里:
while($row = mysqli_fetch_array($query)){
// ...
$query = mysqli_query($dbCon, $sqlThree);
// ...
}
您应该 a) 根本不存储 mysqli_query()
的结果,或者 b) 选择不同的变量名称,例如$update_res = mysqli_query(...);
。
更好的是,使用单个查询即可完成这两项操作:
INSERT INTO totals VALUES (NULL, :branch, 0, :amount, 0, :date)
ON DUPLICATE KEY UPDATE lodgements = :lodgements
只需确保在表上定义了正确的唯一约束即可。
关于php - 将变量值与 PHP 中的查询结果进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21842332/