Jump to content

mysql query with single quotes in a variable


scottnicol

Recommended Posts

$sitedetails = "INSERT INTO vars (address, sitename, description, ownername, theme) VALUES ('$url', '$sitename', '$description', '$ownername', '$theme') ";

mysql_query($sitedetails) or die(mysql_error()); // site details in mysql

 

If say $sitename = "scott nicol's blog"; - this will give me:

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 's blog test', 'scott nicol', 'scott nicol', 'default')' at line 1

 

I know it's due to the single quite in 'nicol's', how do I keep the quote, but stop this error?

 

Since ' surrounds values in MySQL you have to escape strings going into MySQL, this will coincidently also prevent from SQL injections:

 

$sitedetails = "INSERT INTO vars (address, sitename, description, ownername, theme) VALUES ('" . mysql_real_escape_string($url) . "', '" . mysql_real_escape_string($sitename) . "', '" . mysql_real_escape_string($description) . "', '" . mysql_real_escape_string($ownername) . "', '" . mysql_real_escape_string($theme) . "') ";

 

mysql_real_escape_string will prevent from SQL injection and errors resulting in ' being input into the database.

Archived

This topic is now archived and is closed to further replies.

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