Wednesday, August 21, 2013

Single quotes for strings in MySQL query



In MySQL query,   single quotes should be added for strings.
Wrong MYSQL syntax: (need to put a single quote in string test@gmail.com)
SELECT revision FROM cesei_new1.cesei_review_new WHERE module_id=127 AND email=test@example.com ORDER BY revision ASC 
Right  MYSQL syntax:
SELECT revision FROM cesei_new1.cesei_review_new WHERE module_id=127 AND email='test@example.com' ORDER BY revision ASC


We are easy to make this mistake in PHP MYSQL programming. PHP right syntax example:
        $module_id=mysql_real_escape_string(trim($_POST['module_id']));
         $email=mysql_real_escape_string(trim($_POST['email']));
       $sql = "SELECT revision  FROM cesei_review_new WHERE module_id=$module_id AND email='$email' ORDER BY revision ASC";
       $result = mysql_query($sql, $db);
       while ($row = mysql_fetch_assoc($result)) {  
        $revision = $row['revision']+1;
       }


wrong syntax:
       $sql = "SELECT revision  FROM cesei_review_new WHERE module_id=$module_id AND email=$email ORDER BY revision ASC";

 $module_id is a number, we do not have to add single quotes, while $email is a string and we have to add single quotes.

No comments:

Post a Comment