Tim Barclay
Tim Barclay

Reputation: 855

Writing to MySQL from a PHP array in a for loop

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?

Upvotes: 1

Views: 183

Answers (1)

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

You have to use {} for using array in query

$query = "INSERT INTO characters VALUES ('{$this->code[$counter]}')";

Upvotes: 1

Related Questions