serialize() value store, in to a database using update query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • apssiva
    New Member
    • Feb 2011
    • 26

    serialize() value store, in to a database using update query

    Hi,

    I got error message "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Town Donation Draw";s:15:"Hou rs Completed";s:8: "3.000000";s:4: "Year";s:4:"200 9";' at line 1".

    pls correct my mistake.

    Code:
    $m = array();
    foreach($students as $student){
    	if($student['nric'] =='S9221121E'){
    		$m = $student;
    	}
    }
    
    print '<pre>';
    $metamoe = serialize($m);
    print '</pre>';
    
    mysql_query("UPDATE sgc SET meta_moe = '$metamoe' WHERE nric = 'S9221121E' AND name = 'ANG MEI KEE'")or die(mysql_error());
    echo "Successfully";
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    #2
    While it's not required, it's good practice to use backticks (the ` symbol, it's next to the 1 key in the nuber row [not the numpad]) in queries to denote table or column names. For example:

    SELECT * FROM `table`

    As for your query, I don't know how many times I have to explain to people that, while it works, putting variables directly within a string is bad practice. What's probably happening is your $metamoe variable contains a quote somewhere. First off, to fix the string, to embed a variable into a string you should end the string and append the variable with a . (dot):

    $str = "This string has a " . $variable . " in it."

    So your query should look like this:

    Code:
    mysql_query("UPDATE sgc SET meta_moe = '" . $metamoe . "' WHERE nric = 'S9221121E' AND name = 'ANG MEI KEE'") or die(mysql_error());
    Now that that's fixed, you should ALWAYS sanitize your database input. Even if there's no user input, it's just safe to sanitize. PHP has a fantastic mysql method to sanitize sring inputs, mysql_real_esca pe_string():

    Code:
    mysql_query("UPDATE sgc SET meta_moe = '" . mysql_real_escape_string($metamoe) . "' WHERE nric = 'S9221121E' AND name = 'ANG MEI KEE'") or die(mysql_error());
    This will properly escape any characters that would interfere with your query. SQL Injection Prevention 101, but it applies pretty much anywhere, and it should solve your problem.

    Comment

    • apssiva
      New Member
      • Feb 2011
      • 26

      #3
      Hi,

      Thank you for your help. Sure i correct my mistake.

      Regards,
      apssiva.

      Comment

      Working...