iscattered
iscattered

Reputation: 103

Updating a database using arrays

I'm trying to update a database using arrays, but I can't seem to do that. I can only update it using strings, and numbers, but not arrays. Then I tried to echo out the string, number AND the array, just to see if I made an mistake in making the array. Please take a look:

$string = "string";
$num = 10;
$array[0][0] = "array";

echo $string."</br>";
echo $num."</br>";
echo $array[0][0]."</br>";

output:

string
10
array

But inserting data into a table using mysql:

$table = "userLogin";
$column = "username";

Using string:

$query= "INSERT INTO $table($column)VALUES($string)";
$result = mysql_query($query);

Output in table:

string

Using number:

$query= "INSERT INTO $table($column)VALUES($number)";
$result = mysql_query($query);

Output in table:

10

But when you're using an array:

$query= "INSERT INTO $table($column)VALUES($array[0][0])";
$result = mysql_query($query);

Output in table:

There is no change. Why is that? I figure that since all strings, numbers, and arrays can be echo, using the echo command, they can be use likewise when updating a database. But it seems like you can only update them using strings and numbers. Unless, I'm doing something wrong. If I'm doing something wrong, please let me know. Thank you.

Upvotes: 0

Views: 124

Answers (1)

Marc B
Marc B

Reputation: 360742

PHP arrays-in-strings 201 (intermediate level): PHP's string parser is NOT greedy, and by default will ignore multi-dimensional array references inside double-quoted strings.

e.g.

$foo = array();
$foo[0] = array();
$foo[0][1] = 'bar';

echo $foo;          // output: Array
echo "$foo[0]"      // output: Array
echo "$foo[0][1]"   // output: Array[1]
echo "{$foo[0][1]}" // output: bar
      ^----------^
echo $foo[0][1]     // output: bar

If you want to use multidimensional arrays in double-quoted strings, then, as above, you have two choice: Don't, concatenate them into the string; or use the {} notation to force PHP to parse the ENTIRE array reference, not just the first dimension.

The specifics of your problem:

$query= "INSERT INTO $table($column)VALUES($array[0][0])";

actually becomes

$query= "INSERT INTO $table($column)VALUES(Array[0])";
                                           ^^^^^

where Array is an unknown/invalid field name, and [0] is a flat-out syntax error.

Upvotes: 1

Related Questions