Skip to content
Advertisement

mysqli query inside foreach loop- syntax problem

I have the following mysqli query:

$conn = new mysqli("localhost", "xx", "xx", "xx");

foreach ($response as $class) {

    $sqle= "REPLACE INTO `items`
                    (`item_ids`)
                VALUES
                    ('{$class['id']}'";

    if ($conn->query($sqle) === TRUE) {
       //
    } else {
       echo "Problem";
    }
}

This is my database table “items”:

item_ids  |  item_class  |  item_subclass
-------------------------------------------
          |       4       |        5

$response is an API array from where I get the value for the item_ids .

I get the following error:

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 ” at line 4

I don´t understand what is wrong with my syntax here?

If I echo $class['id'] (without the query) in the foreach loop I get the expected values. So it´s a problem with the query inside of it.

Advertisement

Answer

Your SQL query is missing a closing parenthesis.

$sqle= "REPLACE INTO `items`
                    (`item_ids`)
                VALUES
                    ('{$class['id']}'";

should be:

$sqle= "REPLACE INTO `items`
                    (`item_ids`)
                VALUES
                    ('{$class['id']}')";
                                     ^ here

You should learn to use query parameters. Then it would be easier to spot this type of punctuation mistake, without getting visually confused with all the different quotes and curly braces.

prepare() this query:

$sqle= "REPLACE INTO `items`
                    (`item_ids`)
                VALUES
                    (?)";

Then bind the parameter, and execute.

Parameterized queries make it easier to write code without making mistakes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement