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
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]
Link to comment
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" :)
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.