up vote 0 down vote favorite

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.

link|flag

72% accept rate
1  
Protip: using a for-loop will save you 2 lines of code. for ($i = 0; $i < 5; $i++) { ... } – Matt Huggins Oct 18 '09 at 19:51
This solved it. There is an error in the above in the while loop, I don't know what it is. But replacing the while loop with the for loop solves it. – David Willis Oct 18 '09 at 20:13
The error I think btw was $i++ was missing a ; after it. – David Willis Oct 19 '09 at 3:12

4 Answers

up vote 4 down vote

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])."','','')"
link|flag
Or this: "INSERT INTO table VALUES ('','{$name[$i]}','','')" – Matt Huggins Oct 18 '09 at 19:50
That doesn't work either. – David Willis Oct 18 '09 at 19:59
up vote 2 down vote

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].

link|flag
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 Oct 18 '09 at 19:54
up vote 1 down vote

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

link|flag
up vote 0 down vote

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 />"
link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.