SQL语句中的PHP变量

I receive the following error when I use a variable in my SQL statement:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL     server version for the right syntax to use near '1 = 86 WHERE ID = 284' at line 1

The code for the SQL (which is being used in PHP) is:

for($l=0; $l<count($item); $l++) {
$query = "UPDATE  members SET  item" . $l+1 . " = ".$itemID[$l]." WHERE ID = ".$_SESSION['id'];
$result = $mysqli->query($query) or die($mysqli->error);
}

I know that the error isn't coming from the Session Variable, but if is coming from l, I don't know why. I thought I did everything correctly. Why do I receive that error and how to I prevent it?

$query = "UPDATE  members SET  item" . ($l+1) . " = ".$itemID[$l]." WHERE ID = ".$_SESSION['id'];

try this

  $query = "UPDATE  members SET  item'".$l+1."' = '".$itemID[$l]." ' 
            WHERE ID = '".$_SESSION['id']."' ";

or this

 $query = "UPDATE  members SET  item'".$l+1."' = $itemID[$l]
            WHERE ID = '".$_SESSION['id']."' ";

Your query is mixing user data in without proper escaping:

for($l=0; $l<count($item); $l++) {
  /* Use sprintf to avoid injecting arbitrary strings into query */
  $query = sprintf("UPDATE  members SET item%d=? WHERE ID=?", $l + 1);

  /* Prepare the statement and bind specific user data values into placeholders */
  $stmt = $mysqli->prepare($query);
  $stmt->bind_param('is', $itemId[$l], $_SESSION['id']);

  /* Execute and get result */
  $result = $stmt->execute();
}

The or die pattern is about the worst possible way to handle errors. You'd be better off raising exceptions and catching those somewhere you can recover from them and present a user-friendly message.

  1. What you are doing there is very bad style. Think about doing it differently! Hints about mysqli and parameters are all over the answers and comments here.
  2. There is no reason to use a for loop and use count($item) many UPDATE statements when you could do it with 1 (one)!

    UPDATE members SET item1=value1, item2=value2, ... WHERE ID = ".$_SESSION['id'];
    
  3. To find the exact cause of the problem I recommend you output the $query, have a look at it and add it to your question here.
  4. The problem seems to lie with the delimiters " and '.