开发者

Inserting php array data into mysql isn't working

开发者 https://www.devze.com 2022-12-09 07:31 出处:网络
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 wr

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 V开发者_StackOverflow社区ALUES ('','$name[i]','','')";
mysql_query($query);

$i++
}

mysql_close();

Any ideas please? Thank you.


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


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消