【问题标题】:MySQL Error ("Query was empty")?MySQL 错误(“查询为空”)?
【发布时间】:2017-07-10 16:18:21
【问题描述】:

<form method='post' action=''>
    Category name: <input type='text' name='cat_name' />
    Category description: <textarea name='cat_desc' /></textarea>
    <input type='submit' value='Add category' />
</form>

  <?php

  if($_SERVER['REQUEST_METHOD'] != 'POST')

  {
      $catname=mysql_real_escape_string('cat_name');
      $catdesc=mysql_real_escape_string('cat_desc');

      $sql = mysql_query("INSERT INTO fcategories (cat_name, cat_desc) 
      VALUES('','$catname','$catdesc')");

      $result = mysql_query($sql);
      if(!$result)
      {
          //something went wrong, display the error
          echo 'Error' . mysql_error();
      }
      else
      {
        echo 'New category successfully added.';
      }
  }

  ?>

我已包含与数据库的连接。当我运行代码时,我的表单底部有一个错误。

【问题讨论】:

  • 您的代码容易受到SQL injection 攻击。您应该通过mysqliPDO 驱动程序使用带有绑定参数的预处理语句。 This post 有一些很好的例子。
  • 不要使用mysql_* 函数。它们自 v5.5(2013 年 6 月)起已被弃用,自 v7.0(2015 年 12 月)起已被删除。而是将mysqli_*PDO 函数与prepared statementsbound parameters 一起使用。
  • 您声明了两个字段,但提供了三个值。
  • 您指定了 2 个字段名称并传递了 3 个值
  • 您运行了两次查询,因此第二次查询失败。 $sql 要么是 mysql_results,要么为空。

标签: php css mysql html


【解决方案1】:
$sql = "INSERT INTO fcategories (cat_name, cat_desc) 
      VALUES('$catname','$catdesc')" ;

 $result = mysql_query($sql, $dbconnection);

【讨论】:

  • 这些查询(在问题和您的答案中)完全相同相同,而且您的答案中也有两个语法错误。 (编辑:你修复了这些) - 你到底想用 OPs 代码改进什么?
  • 扭转潮流,反对教授/传播草率和危险的编码实践。如果您发布没有准备好的陈述的答案you may want to consider this before posting。另外a more valuable answer comes from showing the OP the right method.
  • 请停止鼓励使用mysql
  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
猜你喜欢
  • 2011-09-02
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 2011-11-13
  • 1970-01-01
相关资源
最近更新 更多