Jump to content

error on this piece of code


kenwvs

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...
Link to comment
https://forums.phpfreaks.com/topic/19971-error-on-this-piece-of-code/
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]
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" :)

Archived

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

×
×
  • Create New...

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.