0

I cant get my code to bind the params to the Mysql Query, what am i doing wrong here?

ERROR

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();
?>
Phil
  • 157,677
  • 23
  • 242
  • 245
Woogygun
  • 1
  • 2
  • Where did you see that you can specify table names as bound parameters? Just wondering if there's a tutorial teaching people such things. – N.B. Aug 20 '13 at 07:59

1 Answers1

1

Tables must not be binded, use this:

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

Also notice you use table where you should use select_table

Marek
  • 7,337
  • 1
  • 22
  • 33