PHP Mysql Auto Quote?

When inserting a string into a mysql database, the string values ​​must be enclosed in quotation marks, where an integer is not needed.

Is there any class or library that takes care of this automatically, so I can just pass the array function of field names and values ​​to a third party and don't have to worry about inserting string values ​​in quotes?

Thank,

+2


source to share


3 answers


You don't just need to worry about quoting; you need to worry about SQL injection.

For new code, use PDO instead of functions mysql_

or mysqli_

. Inside PDO, use prepared statements (object PDOStatement

).



With prepared statements, you never have to quote things and stop SQL injection.

+7


source


If you are using PDO , you don't need to worry about such things.



Have a look at PDO :: prepare for some examples.

+3


source


When I use drupal the db_query("SELECT col FROM tab WHERE id=%d",$id)

default behavior handles this for you.

This is similar to using sprintf

with mysql_real_escape_string

as per your request. And you can implement it yourself, from the code they show , notice that they are using a method preg_replace_callback()

and you can click on it ..

Traditional way if you ignore PDO (not recommended):

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>

      

+1


source







All Articles