简体   繁体   中英

Mysql working correctly but show syntax error

I have a non buggy mysql code (it's working and input correct data into every field)

$sql = "UPDATE bloggers SET img_name = '" . $img_name . "', name = '" . $blogger_name . "', blog_url = '" . $blog_url . "', google_plus = '" . $google_plus . "' WHERE blogger_id = '" . $blogger_id . "'";

        $res = mysql_query($sql);
        if($res) 
        {return 99;}
        else
        {return 0;}

where $res will return 99.

However, it's giving me this error.

Invalid query: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 '1''' at line 1

How do I go about solving this problem?

Let me know! Thanks!

Regards

I think there is a special character in your parameters. So sanitize your params by mysql_real_escape_string . It will prevent sql injection attacks as well.

$img_name = mysql_real_escape_string($img_name);
$blogger_name = mysql_real_escape_string($blogger_name);
$blog_url = mysql_real_escape_string($blog_url);
$google_plus = mysql_real_escape_string($google_plus);

Well to answer your question, you are performing SQL Injection on your own code since on of your variables contain single quote or slash in them.

You need to either escape them using mysql_real_escape_string BUT I would not do that since mysql_* functions have been deprecated.

Use PDO prepared statements or MySQLi instead where i stands for improved.

Using PDO it could be as simple as:

 $stmt = $pdoInstance->prepare("
            UPDATE bloggers 
            SET img_name = :imgname, name = :blogname, 
                blog_url = :blogurl, google_plus = :googleplus
            WHERE blogger_id = :blogid
         ");

  //bind parameters
  $stmt->bindParam(':imgname', $img_name, PDO::PARAM_STR);
  $stmt->bindParam(':blogname', $blogger_name, PDO::PARAM_STR);
  $stmt->bindParam(':blogurl', $blog_url, PDO::PARAM_STR);
  $stmt->bindParam(':googleplus', $google_plus, PDO::PARAM_STR);
  $stmt->bindParam(':blogid', $bloger_id, PDO::PARAM_INT);

  if ($stmt->execute()) {
     //success
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM