我一直在开发一个将数据添加到数据库的表单。我进行了验证,让用户知道字段是否为空或无效。一旦所有内容都经过验证,我想将其提交到数据库。我当前的代码验证数据但无论如何都会提交。这可能是我的逻辑和 if else 语句中的一个缺陷,但我似乎无法让它工作。
这是部分代码,包括一些验证和 INSERT 语句。
// Quantity
if (empty($_POST["qtyAdd"]))
{
$qtyErr = "Please enter a product quantity";
}
else
if (!is_numeric($year))
{
$qtyErr = "Data entered was not numeric";
}
else
if (strlen($number) != 3)
{
$qtyErr = "The number entered was not 3 digits long";
}
else
{
$qty = test_input($_POST["yearAdd"]);
}
// Featured
if (empty($_POST["featuredAdd"]))
{
$featuredErr = "Feature Item?";
}
else
{
$featured = test_input($_POST["featuredAdd"]);
}
//Add to database
{
$sql = "INSERT INTO tbl_products (product_name, product_description, product_price, product_year, product_show, product_type, product_signed, product_quantity, product_featured, product_img) VALUES ('$name', '$desc', '$price', '$year', '$show', '$cat', '$signed', '$qty', '$featured', $img)";
mysql_query($sql);
}
}
最佳答案
你懒得去检查是否有错误。这就是为什么您的查询始终被执行的原因:
if (!isset($qtyErr) && !isset($featuredErr)) {
$sql = "INSERT INTO tbl_products (product_name, product_description, product_price, product_year, product_show, product_type, product_signed, product_quantity, product_featured, product_img) VALUES ('$name', '$desc', '$price', '$year', '$show', '$cat', '$signed', '$qty', '$featured', $img)";
mysql_query($sql);
}
关于PHP 验证后提交到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112323/