Jump to content


Photo

error on this piece of code


  • Please log in to reply
3 replies to this topic

#1 kenwvs

kenwvs
  • Members
  • PipPipPip
  • Advanced Member
  • 194 posts

Posted 07 September 2006 - 01:17 AM

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);  

} 


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

#2 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 07 September 2006 - 01:26 AM

in your query you have .'',',

try this...

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);  

}

follow me on twitter @PHPsycho

#3 btherl

btherl
  • Staff Alumni
  • Advanced Member
  • 3,893 posts
  • LocationAustralia

Posted 07 September 2006 - 03:09 AM

To avoid problems like this in future, I recommend you split such code over multiple lines.  For example:

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);  
}

This makes it easier to see errors.

Another nice convention is:

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);  
}

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

#4 kenwvs

kenwvs
  • Members
  • PipPipPip
  • Advanced Member
  • 194 posts

Posted 07 September 2006 - 05:34 AM

That solved this particular problem....Thank You very much.  I am going to post another question regarding this.....




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users