[英]Incrementing array index in SQL statement throws error
I want to insert
into sql database , the items in the array. 我想insert
数组中的项目insert
sql数据库。 All I am doing is incrementing the index of array in INSERT
command ( cash[$i+1]
) using for
loop. 我所要做的就是使用for
循环在INSERT
命令( cash[$i+1]
)中增加数组的索引。 But it shows an error : 但是它显示了一个错误:
unexpected '+', expected ']' 意外的“ +”,预期的“]”
How can I solve this problem? 我怎么解决这个问题?
for($i = 0; $i < count($cash_list); $i = $i+8) {
$sql = "INSERT INTO Payments VALUES('$cash_list[$i]','$cash_list[$i+1]','$cash_list[$i+2]','$cash_list[$i+3]','$cash_list[$i+4]','$cash_list[$i+5]','$cash_list[$i+6]','$cash_list[$i+7]')";
if (mysqli_query($con, $sql))
echo "yes";
else
echo "Error: " . $sql . "<br>" . $con->error;
}
This is because 这是因为
$i+1
Doesn't get interpreted as math expression. 不会被解释为数学表达式。 It's just a string. 这只是一个字符串。 So you would have to concatenate your strings like this: 因此,您必须像这样连接字符串:
$sql = "INSERT INTO Payments
VALUES('" . $cash_list[$i] . "',
'" . $cash_list[$i+1] . "',
'" . $cash_list[$i+2] . "',
'" . $cash_list[$i+3] . "',
'" . $cash_list[$i+4] . "',
'" . $cash_list[$i+5] . "',
'" . $cash_list[$i+6] . "',
'" . $cash_list[$i+7] . "'
)";
Also you might want to take a look into: mysqli_* prepared statements
which is much safer! 另外,您可能想看看: mysqli_* prepared statements
更安全! (Also please take the count($cash_list)
out of your loop condition and put it into a variable and then use the variable in the condition) (还请从循环条件中取出count($cash_list)
并将其放入变量中,然后在条件中使用该变量)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.