我有一个HTML表单;我希望能够设置它,以便如果一个字段为空,DB中的字段实际上将为NULL,而不是在字段中只有NULL。我认为使用这段代码会有所帮助,但它只是在字段中输入NULL。 PHP代码:
<pre>
<?php
if (isset($_POST['oc_item'])) {
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? $_POST['oc_itemdesc'] : NULL;
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES(''$oc_item','$oc_itemdesc')";
mysql_query($SQL);
if (mysql_query($sql)) {
echo '<strong><em>Your data has been submitted</em></strong><br /><br />';
} else {
echo '<p>Error adding submitted info: ' . mysql_error(). '</p>';
}
}
?></pre>
HTML代码:
<pre>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Item Name</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_item" /></td>
</tr>
<tr>
<td>Item Description</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_itemdesc" /></td>
</tr>
</table>
<p><input type="submit" value="Submit item" /></p>
</form></pre>
我希望该字段实际上是 NULL ,而不是该字段包含单词NULL。提前谢谢。
答案 0 :(得分:1)
如果您打印出$ sql,您会看到它正在插入, 'NULL'
。
您需要修改代码,使其插入工作“NULL”(不带''引号),或者更好的是,根本不插入该参数(消除整个{{1字符串的一部分。
答案 1 :(得分:1)
如果要将NULL写入MySQL数据库,则必须在不带引号的位置放置NULL。
像这样:
INSERT INTO table (column, column2) VALUES ('mystring', NULL);
如果您想手动手动执行此操作总是有点费力,因为您必须为查询创建if条件。
记住:PHP null
!= MySQL NULL
。他们俩根本不认识对方。
但我仍在疑惑,这与问题名称有什么关系? (除非选择)
您可以像这样编写代码:
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (isset($_POST['oc_itemdesc']) && trim($_POST['oc_itemdesc']) != '') ? "'" . mysql_escape_string($_POST['oc_itemdesc']) . "'" : 'NULL';
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('" . $oc_item . "', " . $oc_itemdesc . ")";
# sorry for adding " . all the time, but I dislike variables within strings :D
但是我不得不承认我也不喜欢那么多,因为它要把MySQL字符串的引号括起来,远离SQL查询本身。
答案 2 :(得分:0)
试试这个:
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? "'".$_POST['oc_itemdesc']."'" : "NULL";
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item',$oc_itemdesc)";
目前您正在添加'NULL'
而不是NULL
,因此它会添加单词而不是值。
旁注:我会小心并正确地转义/编码$_POST['oc_itemdesc']
,因为在描述中放入撇号的人会完全抛弃插入语句。例如:I don't like this
看起来像这样:
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item','I don't like this')";//MYSQL Error
PPS:目前您正在插入TWICE:
mysql_query($SQL);//insert 1
if (mysql_query($sql)) {//insert 2
答案 3 :(得分:0)
我用于HTML表单中的MySQL数据的函数。
function emptyHtmlFormToNull($arr){
foreach($arr as $key => $val){
if(empty($val) || strtolower($val) === 'null'){
$arr[$key] = null;
}
}
return $arr;
}