【问题标题】:Why is my PHP prepared statement for MySQL not working?为什么我的 PHP 为 MySQL 准备的语句不起作用?
【发布时间】:2010-10-11 17:01:29
【问题描述】:

我目前正在学习 PHP 和 MySQL。我刚刚编写了一个处理所有 MySQL 流量的类,但遇到了一些错误。

function table_exists($tablename){
    // check if table exists
    $stmt = $this->db->prepare("SHOW TABLES LIKE '?'");
    $stmt->bind_param("s", $tablename); //This is line 24.
    $stmt->execute();
    $ar = $stmt->affected_rows;
    $stmt->close();
    if ($ar > 0){
        return true;
    } else {
        return false;
    }
}

这是有问题的代码,我得到的错误是

产生警告: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]:数量 变量与数量不匹配 准备好的语句中的参数 C:\xampp\htdocs\mail\datahandler.php 第 24 行

想法?

谢谢

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    使用准备好的语句时无需使用引号。

    $stmt = $this->db->prepare("SHOW TABLES LIKE ?");
    

    此外,您可能希望使用 information_schema 视图而不是 SHOW TABLES,这为您提供了更多的灵活性。

    【讨论】:

    • 这是否意味着如果我这样做,我也不需要报价? $query = "从邮件列表中删除,其中 id='?'和” 。 "password='PASSWORD(?)'";
    • 使用你的代码后,我得到你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在“?”附近使用的正确语法在第 1 行
    • 也许 SHOW TABLES 不支持 LIKE 子句中的预处理语句...尝试SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? 其中TABLE_SCHEMA 是您的数据库名称,TABLE_NAME 是您的表名称。
    【解决方案2】:

    您还必须使用数字作为 bind_param() 的第一个参数

    $stmt->bind_param(1, $tablename);
    

    请看这里:http://php.net/manual/pdostatement.bindparam.php

    对于字符串,您也可以只将数组传递给 execute()。

    【讨论】:

    • 好吧,我没有意识到你在使用 MySQLi,我以为你在使用 PDO - 我强烈推荐顺便说一句。
    【解决方案3】:
    private function table_exists($tablename){
            // check if table exists
            $stmt = $this->db->query("SHOW TABLES");
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                $arr[]=$row;
            }
            $ar=0;
            foreach($arr as $val){
                foreach($val as $value){
                    if($value==$tablename) $ar=1;
                }
            }
            unset($stmt);
            if ($ar == 1){
                return true;
            } else {
                return false;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多