2012-07-07 30 views
1

如何在SQL查詢中傳遞「NULL」或「字符串」。在mysql中插入查詢字符串中的NULL或'string'

例如(城市是可選的並且可以NULL在MySQL使用)

<?php 
$var = !empty($_POST['city']) ? $_POST['city'] : NULL; 
$query = mysql_query("INSERT INTO table VALUES('".$_POST['firstname']."','".$var."')"); 
?> 

這不是工作,怎麼一回事,因爲NULL和「NULL」(作爲字符串)不爲MySQL相同。

+0

**你的代碼是脆弱的到SQL注入。**你真的應該使用[prepared statements](http://stackoverflow.com/a/60496/623041),將你的變量作爲參數傳遞給它,而這些參數不會被SQL評估。如果你不知道我在說什麼,或者如何解決它,請閱讀[Bobby Tables]的故事(http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain) 。 – eggyal 2012-07-07 16:05:21

+0

另外,正如在['mysql_query()'](http://php.net/manual/en/function.mysql-query.php)函數的PHP手冊中所述:*不推薦使用此擴展名。相反,[MySQLi](http://www.php.net/manual/en/book.mysqli.php)或[PDO_MySQL](http://www.php.net/manual/en/ref.pdo-應該使用mysql.php)擴展名。另請參見[MySQL:選擇API](http://www.php.net/manual/en/mysqlinfo.api.choosing.php)指南和[相關FAQ](http://www.php.net/manual /en/faq.databases.php#faq.databases.mysql.deprecated)以獲取更多信息。* – eggyal 2012-07-07 16:05:31

回答

4

不要圍繞NULL與查詢報價:

$var = !empty($_POST['city']) ? ("'" . $_POST['city'] . "'") : 'NULL'; 
$query = mysql_query("INSERT INTO table VALUES('".$_POST['firstname']."',".$var.")"); 

現在,如果沒有指定$_POST['city']時,您的查詢會是這個樣子:

INSERT INTO table VALUES('nickb',NULL) 
相關問題