0

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.

3
  • 1
    Protip: using a for-loop will save you 2 lines of code. for ($i = 0; $i < 5; $i++) { ... } Commented Oct 18, 2009 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. Commented Oct 18, 2009 at 20:13
  • The error I think btw was $i++ was missing a ; after it. Commented Oct 19, 2009 at 3:12

4 Answers 4

5

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])."','','')"
Sign up to request clarification or add additional context in comments.

1 Comment

Or this: "INSERT INTO table VALUES ('','{$name[$i]}','','')"
2

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

1 Comment

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

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.