2013-08-20 148 views
0

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

错误

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in /Users/warren/Sites/Frame Work/Modules/User Login/classes/db.php:34 Stack trace: #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} thrown in /Users/warren/Sites/Frame Work/Modules/User Login/classes/db.php on line 34

CODE

<?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(); 
?> 
+0

你从哪里看到可以指定表名作为绑定参数?只是想知道是否有教程教人们这样的事情。 –

回答

1

表不能绑定,使用此:

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

还要注意使用表,你应该使用select_table