Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape quotes when inserting into database with PHP [duplicate]

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');
like image 717
Mauro74 Avatar asked Apr 07 '10 12:04

Mauro74


People also ask

How do you escape quotes in 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.

How do you escape a single quote in SQL?

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.

How do I allow a single quote in a MySQL query?

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.


1 Answers

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);
like image 200
Tomalak Avatar answered Oct 05 '22 18:10

Tomalak