tags:

views:

120

answers:

4

Hello I have an array $name[] that I am trying to insert into the second field of my table but it's not working (table remains completely blank). I cannot find the error in my code what am I doing wrong?

$username="us";
$password="pw";
$database="db";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "error");

$i=0;
while ($i < 5) {


$query = "INSERT INTO table VALUES ('','$name[i]','','')";
mysql_query($query);

$i++
}

mysql_close();

Any ideas please? Thank you.

+4  A: 

You used a constant i instead of $i for the key of $name. So try this:

"INSERT INTO table VALUES ('','".$name[$i]."','','')"

You should also escape the value for the MySQL query using mysql_real_escape_string:

"INSERT INTO table VALUES ('','".mysql_real_escape_string($name[$i])."','','')"
Gumbo
Or this: "INSERT INTO table VALUES ('','{$name[$i]}','','')"
Matt Huggins
That doesn't work either.
David Willis
A: 

Try running the query like this:

mysql_query($query) or die(mysql_error());

This will give you a better idea of what you're doing wrong if there's a problem with your query. You may also want to print your SQL for debugging:

echo "Query $i: $query<br />"
yjerem
+2  A: 

Well, first, all that will do is put an entry with columns 1, 3, and 4 blank, and column 2 with the value $name[i]. To have a variable in a string, it needs to be in double quotes. But I don't see the point of doing that when you can just have the variable.

Also, $name[i] is supposed to be $name[$i].

nasufara
I changed it to $name[$i] and it made no difference. I am leaving the other columns blank for now as I try and just get one column of data in and when it works I can get my other arrays into the columns.
David Willis
+1  A: 

Make sure to escape when you are concatenating queries like that.

$query = "INSERT INTO table VALUES ('', '" . mysql_real_escape_string($name[$i]) . "', '', '')";

If you don't you might be vulnerable to SQL injection badness

Jason Keene