我正在网络上做一个 php 教程,一切顺利,直到在表单条件中使用 isset 向数据库插入内容。好吧,让我们来看看代码:
这是插入数据库函数(在 functions.php 中)
function addCat($cName, $cDesc){
$query = mysql_query("INSERT INTO categories (Title, Description) VALUES ('$cName','$cDesc')") or die (mysql_error());
}
这是表格:
<form action="doAdd.php" method="post">
<table>
<tr>
<td><label for="CatName">Name</label></td>
<td><input type="text" name="CatName" /></td>
</tr>
<tr>
<td><label for="CatDesc">Description</label></td>
<td><input type="text" name="CatDesc" /></td>
</tr>
<tr><td colspan="2"><input type="submit" value="submit" name="submit"/></td></tr>
</table>
</form>
这是表单的操作(在 doAdd.php 中):
<?php
include('includes/functions.php');
if(isset($_POST['submit'])) {
if(isset($_POST['CatName'])){
addCat($_POST['CatName'],$_POST['CatDesc']);
header("Location: cats.php");
} else {
echo "please set a category name!";
}
} else {
header("Location: addCat.php");
}
?>
所以关于表单的事情是它插入空白字段,在数据库中创建空白记录。你认为isset的问题是什么?
最佳答案
您应该以这种方式使用 empty()
而不是 isset()
:
if(! empty($_POST['CatName']))
empty
测试 var 是否已设置且不为空(即不是 ''
和明显的其他值,如 0、false 等)。
关于php - 设置();不返回 false 并将空白字段插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8369984/