1

I'm having a bit of trouble writing the contents of a PHP array to rows of a column in a MySQL table. Instead of updating each time through the loop, the same things gets inserted into the database again and again.

Here's the code ($code is an array of characters and $code_length is its length):

for ($counter = 0; $counter < $this->code_length; $counter++){
    $query = "INSERT INTO characters VALUES ('$this->code[$counter]')";
    mysql_query($query, $db_server);
}

If I execute it like this, it just puts the first element of $code on every line of the table. However, if I just change it to use a reference to the array element outside the SQL query instead it works. For example:

for ($counter = 0; $counter < $this->code_length; $counter++){
    $code_element = $this->code[$counter];
    $query = "INSERT INTO characters VALUES ('$code_element')";
    mysql_query($query, $db_server);
}

works fine and puts each new element of $code in a new row.

Can anyone see what I'm doing wrong in the first example or can you just not refer to array elements in that way in MySQL queries?

3

1 Answer 1

1

You have to use {} for using array in query

$query = "INSERT INTO characters VALUES ('{$this->code[$counter]}')";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.