0

我无法让我的代码将参数绑定到 Mysql 查询,我在这里做错了什么?

错误

致命错误:未捕获的异常“PDOException”和消息“SQLSTATE [HY093]:无效的参数号:绑定变量的数量与 /Users/warren/Sites/Frame Work/Modules/User Login/classes/db 中的令牌数量不匹配” .php:34 堆栈跟踪:#0 /Users/warren/Sites/Frame Work/Modules/User Login/classes/db.php(34): PDOStatement->execute() #1 /Users/warren/Sites/Frame Work /Modules/User Login/classes/db.php(48): dbConnect->get_contents() #2 {main} 在 /Users/warren/Sites/Frame Work/Modules/User Login/classes/db.php 上线34

代码

<?php 
include '../../../../config.php';

$dbUser = $config['username'];
$dbPass = $config['password'];

class dbConnect {

    public function connect($dbUser,$dbPass) {
        $this->dbUser = $dbUser;
        $this->dbPass = $dbPass;
        try {
            $this->connect = new PDO('mysql:hostname=localhost;dbname=totalrisk', $this->dbUser, $this->dbPass);
            $this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $this->connect;
        } catch (Exception $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

    public function select_table($table) {
        $this->select_table = $table;
        echo $this->select_table;
    }

    public function select_col($col) {
        $this->select_col = $col;
        echo $this->select_col;
    }

    public function get_contents() {
        $stmt = $this->connect->prepare('SELECT * FROM :table');
        $stmt->bindParam(':table', $this->table , PDO::PARAM_STR);
             $stmt->execute();

             $result = $stmt->fetchAll();

             while($row = $stmt->fetch()) {
                print_r($row);
             }
    }
}

$conn = new dbConnect();
$conn->connect($dbUser,$dbPass);
$conn->select_table('users');
$conn->select_col('site_name');
$conn->get_contents();
?>
4

1 回答 1

1

表不能被绑定,使用这个:

$this->connect->prepare('SELECT * FROM ' . $this->select_table);

另请注意,您在应该使用 select_table 的地方使用 table

于 2013-08-20T07:32:01.367 回答