David Willis
David Willis

Reputation: 1092

Inserting php array data into mysql isn't working

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.

Upvotes: 0

Views: 589

Answers (4)

Jason Keene
Jason Keene

Reputation: 1125

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

Upvotes: 1

user153498
user153498

Reputation:

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

Upvotes: 2

Paige Ruten
Paige Ruten

Reputation: 176635

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

Upvotes: 0

Gumbo
Gumbo

Reputation: 655129

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])."','','')"

Upvotes: 5

Related Questions