views:

306

answers:

3

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,

+3  A: 

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

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

Ólafur Waage
+1  A: 

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));
?>
dlamblin
+4  A: 

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.

Nate