PHP 验证后提交到数据库

标签 php mysql validation

我一直在开发一个将数据添加到数据库的表单。我进行了验证,让用户知道字段是否为空或无效。一旦所有内容都经过验证,我想将其提交到数据库。我当前的代码验证数据但无论如何都会提交。这可能是我的逻辑和 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/

相关文章:

php - PHPWord 的 HTML 阅读器不能处理表格?

php - 有没有比 fopen() 更快的函数?

php - 使用php将日期时间保存在mysql中

mysql - 为什么 MySQL 会在 varchar 字段中正确保存 "™",但在文本字段中保存为 "â„¢"?

mysql - Sql 查询在 group by 上花费太多时间

mysql - 是否有任何 SQL 验证器可以针对多个数据库服务器检查语法?

php - 我想改进 http ://www. go4film.com 中的搜索功能

php - 如何正确编写查询 SELECT'ing 多个表

ruby-on-rails - Ruby on Rails I18n 插值

node.js - 如何在@hapi/joi中设置自定义错误消息?