开发者

Why is my PHP prepared statement for MySQL not working?

I'm currently learning PHP and MySQL. I'm just wrote a class that handles all the MySQL traffic, but I'm encountering some errors.

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;
    }
}

This is the code with the problem, and the error i'm getting is

Generates Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\mail\datahandler.php on line 24

Ideas?

Thanks


No need to use quotes when working with prepared statements.

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

Also, instead of SHOW TABLES, you might want to use information_schema views, which give you a bit more flexibility.


You also have to use a number as first parameter for bind_param()

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

See here: http://php.net/manual/pdostatement.bindparam.php

For strings you can also just pass an array into execute().


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;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜