【问题标题】:PHP function returning MySQL syntax error [duplicate]PHP函数返回MySQL语法错误[重复]
【发布时间】:2020-11-08 15:06:07
【问题描述】:

我认为这里没有太多要解释的。代码一目了然。

这个函数我写了

function checkDuplicate($table, $field, $value){
  global $pdo;
  $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM :table WHERE :field = :value");
  $stmt-> bindValue(':table', $table);
  $stmt-> bindValue(':field', $field);
  $stmt-> bindValue(':value', $value);
  $stmt-> execute();
  $f = $stmt->fetch();

  if($f['cnt'] > 0){
    return 1;
  }else{
    return 0;
  }
}

我这样称呼它

if(checkDuplicate("members", "mem_uname", $uname) == 1){
  echo alert_danger("An account with this username already exists.");
  exit();
}

调用返回此错误

Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''members' WHERE 'mem_uname' = 'shrey'' at line 1 in E:\xampp\htdocs\buxhost\includes\functions.php on line 35

我的错误是什么?为什么我会收到这个错误?据我多次检查,我的代码中没有发现任何明显错误。

【问题讨论】:

  • 表名不能是参数。

标签: php mysql sql pdo


【解决方案1】:

您不能将表名设置为参数。您必须在准备语句中传递它。

function checkDuplicate($table, $field, $value){
  global $pdo;
  $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM `$table` WHERE `$field`= :value");
  $stmt->bindValue(':value', $value);
  $stmt->execute();
  $f = $stmt->fetch();

  if($f['cnt'] > 0){
    return 1;
  }else{
    return 0;
  }
}

编辑:无法将字段名称设置为参数。

【讨论】:

  • 后来才知道,也不能设置字段名作为参数。因此,我编辑了答案。
  • @RedStarEntertainment 我在发布答案时没有注意到这一点。我已接受您的修改。
  • 没关系.. 谢谢:)
猜你喜欢
  • 1970-01-01
  • 2021-01-04
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 1970-01-01
  • 2014-08-08
相关资源
最近更新 更多