简体   繁体   中英

PHP Mysql Auto Quote?

When inserting a row in mysql database, string values need to be enclosed in quotes where integer don't need to.

Is there any class or library that takes care of this automatically so that I can just pass to a 3rd-party function an array of fieldnames and values and don't have to worry about putting string values in quotes?

Thanks,

You need to worry about more than just quoting; you need to worry about SQL injection.

For new code, use PDO instead of the mysql_ or mysqli_ functions. Within PDO, use prepared statements (the PDOStatement object).

With prepared statements, you never have to enclose things in quotes and it stops SQL injections.

If you use PDO , then you do not need to worry about things like that.

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

When I'm using drupal, the default behavior of db_query("SELECT col FROM tab WHERE id=%d",$id) handles that for you.

This is similar to using sprintf with mysql_real_escape_string on your query first. And you could implement it yourself, from the code they show , note that they use the preg_replace_callback() method, and you can click on that..

The 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));
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM