Jump to content

Archived

This topic is now archived and is closed to further replies.

kenwvs

error on this piece of code

Recommended Posts

[code]foreach($_POST['description'] as $key=>$description) { 
  $query='INSERT INTO table (description,number) VALUES (\''.mysql_real_escape_string($description).'','.intval($_POST['number'][$key].')'; 
mysql_query($query) or die(mysql_error().$query); 

}  [/code]

is there something missing in this code.... when I try to use it, it complains about an unexpected comma, but if I remove the comma in there, it still complains about an unexpected error. With it in with the rest of my code, it causes all php code after it to not function in php....example my mysql_query are not working after this peice of code...

Share this post


Link to post
Share on other sites
in your query you have .'',',

try this...

[code]foreach($_POST['description'] as $key=>$description) { 
  $query = "INSERT INTO table (description,number) VALUES ('" . mysql_real_escape_string($description) . "','" . intval($_POST['number'][$key] . "')"; 
mysql_query($query) or die(mysql_error().$query); 

}[/code]

Share this post


Link to post
Share on other sites
To avoid problems like this in future, I recommend you split such code over multiple lines.  For example:

[code]foreach($_POST['description'] as $key=>$description) { 
  $query = "INSERT INTO table (description,number) VALUES ('"
  . mysql_real_escape_string($description) . "', "
  . intval($_POST['number'][$key] . " )"; 
  mysql_query($query) or die(mysql_error().$query); 
}[/code]

This makes it easier to see errors.

Another nice convention is:

[code]foreach($_POST['description'] as $key=>$description) {
  $description_esc = mysql_real_escape_string($description);
  $number = intval($_POST['number'][$key]);
  $query = "INSERT INTO table (description,number) VALUES ("
    . "'{$description_esc}', "
    . "{$number} )";
mysql_query($query) or die(mysql_error().$query); 
}[/code]

This code is much easier to read.  And "easy to read" means "fewer bugs" :)

Share this post


Link to post
Share on other sites
That solved this particular problem....Thank You very much.  I am going to post another question regarding this.....

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.