Page 1 of 1

Eascaping quotes in mysql query

Posted: Tue Apr 23, 2013 10:15 am
by spacebiscuit
Hi,

how do I escape a sting in an myslq statement:

I tried:

Code: Select all

$query="DELETE FROM `table1` WHERE id=$_POST[\'ID\']";

$query="DELETE FROM `table1` WHERE id=$_POST[\"ID\"]";
I get white space errors with the above.

Thank you.

Re: Eascaping quotes in mysql query

Posted: Tue Apr 23, 2013 12:48 pm
by Celauran
Depends on your database extension. You'd do better to use PDO with prepared statements.

Code: Select all

$query = "DELETE FROM table1 WHERE id = :id";
$stmt = $pdo->prepare($query);
$stmt->execute(array(':id' => $_POST['ID']));

Re: Eascaping quotes in mysql query

Posted: Wed Apr 24, 2013 1:33 am
by social_experiment
if you still use mysql look at mysql_real_escape_string(). You should upgrade to prepared statements as Celauran suggests or at least use mysqli functions when interacting with the database.

Code: Select all

<?php
  $id = mysql_real_escape_string($_POST['ID']);
  $sql = "DELETE FROM `table1` WHERE id = $id";  
?>

Re: Eascaping quotes in mysql query

Posted: Wed Apr 24, 2013 1:43 am
by spacebiscuit
I found that surrounding the var with curly brackets also worked, is this an acceptiable method?

Thanks.

Re: Eascaping quotes in mysql query

Posted: Wed Apr 24, 2013 2:46 am
by social_experiment
not if you want to secure the query against injection attacks but i suspect your question wasn't about a security related issue :)

Re: Eascaping quotes in mysql query

Posted: Wed Apr 24, 2013 4:13 am
by spacebiscuit
For now it was a question just about how to stop the error from tripping up my script, I will work on the SQL injection stuff next.

Is the mysql_real_escape_string function sufficient to protect against SQL injection attempts?

Thanks.

Re: Eascaping quotes in mysql query

Posted: Thu Apr 25, 2013 1:08 am
by social_experiment
spacebiscuit wrote:Is the mysql_real_escape_string function sufficient to protect against SQL injection attempts?
i'm going to say no, the url below gives a few things to look at when defending against injection attempts; it's not php specific but the ideas behind the examples can easily be applied in php aswell
https://www.owasp.org/index.php/SQL_Inj ... heat_Sheet