簡體   English   中英

在SQL語句中增加數組索引會引發錯誤

[英]Incrementing array index in SQL statement throws error

我想insert數組中的項目insert sql數據庫。 我所要做的就是使用for循環在INSERT命令( cash[$i+1] )中增加數組的索引。 但是它顯示了一個錯誤:

意外的“ +”,預期的“]”

我怎么解決這個問題?

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;
}

這是因為

$i+1

不會被解釋為數學表達式。 這只是一個字符串。 因此,您必須像這樣連接字符串:

$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] . "'
       )";

另外,您可能想看看: mysqli_* prepared statements更安全! (還請從循環條件中取出count($cash_list)並將其放入變量中,然后在條件中使用該變量)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM