views:

48

answers:

2

I want to have a generic PHP function that builds a mysql query based on the parameters of the function. Since it is generic the query may sometimes ask for id=123 or name='Bob'. I test out some queries with quotes around numbers, even stuff like WHERE id > '50' + 7 and it worked but I have my doubts that this won't cause trouble down the road. I guess if this is really an all purpose function it should be able to handle dates and whatever other datatypes there are. So what would be the best way to form these queries safely?

+4  A: 

Quotes around values are fine for any type. The way the values will be treated will depend on the type of the field it's compared against. If necessary, they will be converted automatically.

As an aside, you may want to look into database wrappers that offer prepared statements like PDO. Apart from other advantages, they will take care of the quoting - and the escaping of incoming data - themselves.

An example from the manual:

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>
Pekka
OK thanks, I thought quotes where only for strings. Learned something new.
Moss
+1  A: 

No quotes do no harm to any of data type. Because, mysql engine will convert it to corresponding columns' data type.

Sadat