Pwnna
Pwnna

Reputation: 9528

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

Upvotes: 2

Views: 1309

Answers (3)

JoinTees
JoinTees

Reputation: 1

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

Upvotes: 0

DanMan
DanMan

Reputation: 11561

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().

Upvotes: 2

Mchl
Mchl

Reputation: 62359

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.

Upvotes: 3

Related Questions