I'm having an error message when inserting content which contains quotes into my db. here's what I tried trying to escape the quotes but didn't work:
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$nowdate = date('d-m-Y')
$title = sprintf($_POST[title], mysql_real_escape_string($_POST[title]));
$body = sprintf($_POST[body], mysql_real_escape_string($_POST[body]));
$sql="INSERT INTO articles (title, body, date) VALUES ('$title','$body','$nowdate'),";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header('Location: index.php');
Escape Sequences In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.
QUOTE () function in MySQL This function in MySQL is used to return a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\), single quote ('), ASCII NULL, and Control+Z preceded by a backslash.
Please start using prepared parameterized statements. They remove the need for any SQL escaping woes and close the SQL injection loophole that string-concatenated SQL statements leave open. Plus they are much more pleasing to work with and much faster when used in a loop.
$con = new mysqli("localhost", "u", "p", "test");
if (mysqli_connect_errno()) die(mysqli_connect_error());
$sql = "INSERT INTO articles (title, body, date) VALUES (?, ?, NOW())";
$stmt = $con->prepare($sql);
$ok = $stmt->bind_param("ss", $_POST[title], $_POST[body]);
if ($ok && $stmt->execute())
header('Location: index.php');
else
die('Error: '.$con->error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With