So I’m having some trouble putting an array into a MySQL table. My goal is to put one element from the array into one row of the table, but that’s not what happens.
$cnt = count($array);
for($i = 0; $i < $cnt; $i++)
{
mysql_query("
INSERT INTO $groupname (id, name)
VALUES('', '".$array[$i]."')
", $conn1);
}
(The id is auto incrementing)
I was hoping that this would put the first element of the array in the first row of the table, the second element in the second row and so on and so forth. Instead, my table looks like this
+----+-------+
| id | name |
+----+-------+
| 1 | Array |
+----+-------+
I’m assuming that it’s just taking the array and putting the whole thing is the first row. How do I prevent that? How would I do one element per row?
EDIT
Here is the var_dump
array(1) { [0]=> array(5) { [0]=> string(1) "0" [1]=> string(1) "1" [2]=> string(1) "2" [3]=> string(1) "3" [4]=> string(1) "4" } }
For testing purposes I just put numbers 0-4 in each element of the array in ascending order
A couple of things to point out:
Don’t call out your id value to insert.
It looks like
$array[$i]is itself an array, so make sure you are using the right value.You should just build your insert query and insert once (see example below).
You really need to look into using
mysqli_*functions instead ofmysql_*as these are deprecated.You really should add error handling on your query (i.e. handle cases where query doesn’t work and give yourself an error message.