Reputation: 2742
I have a function which adds varhcars and integers into a database row
public function addItem($id, $site, $price, $quantity, $condition,
$sellerName, $sellerRating, $sellerLocation, $description, $link){
$q = "INSERT INTO tbl_items VALUES(
'$id',
'$site',
$price,
$quantity,
'$condition',
'$sellerName',
$sellerRating,
'$sellerLocation',
'$description',
'$link',
".time().")";
return mysql_query($q, $this->connection);
}
There may be situations where I may decide that I want to set a varchar value to NULL, but the problem is if I send the string NULL as a parameter it will always be treated as a string.
e.g.
addItem("id1", "site1", 100, NULL, "NULL", "NULL", "NULL", "NULL", "NULL", "NULL",);
How do I avoid NULL being treated a string in my query?
Upvotes: 0
Views: 81
Reputation:
Easy. Don't quote it, as 'NULL'
is always a string and NULL
is .. well, NULL.
How? Use placeholders aka prepare statements.
This will take care of any quoting (as required) and prevent SQL injection attacks. Win.
See How can I prevent SQL injection in PHP? which contains information on writing safe queries and has examples for both mysqli and PDO approaches.
Upvotes: 6