Invalid statement / prepare while doing SELECT on class
What's wrong with this class?
<?php
class myClass {
private $dbServer = 'localhost';
private $dbUser = 'db_name';
private $dbPass = 'db_pass';
private $dbName = 'db_name';
var $error = NULL;
var $db;
function connect()
{
// improved by http://stackoverflow.com/users/618622/bv202
try
{
$this->db = new PDO('mysql:host=' . $this->dbServer . ';dbname=' . $this->dbName, $this->dbUser, $this-开发者_运维问答>dbPass);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return (!$this->db) ? FALSE : TRUE;
$this->db = NULL;
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
function columns($table)
{
if(!$this->connect()) $this->error = 'Error connecting/creating PDO.';
else
{
$columnsTable = $this->db->prepare("DESCRIBE :_table"); // here points out the error
if(!$columnsTable) $this->error = 'Invalid statement';
else
{
$columnsTable->bindParam(':_table', $table);
if(!$columnsTable->execute()) $this->error = 'Error while executing statement.';
else
{
$columns = $columnsTable->fetchAll();
if(!$columns) $this->error = 'Invalid fetch.';
else
{
$columnsTable->closeCursor();
foreach($columns as $column=>$columnData)
{
$results[] = $columnData['COLUMN_NAME'];
}
}
}
$columnsTable = NULL;
}
}
return !empty($this->error) ? $this->error : $results;
}
}
$control = new myClass;
$content = $control->columns('customers');
var_dump($content);
?>
Outputs:
string(17) "Invalid statement"
I tested the SQL directly on MySQL without errors.
MySQL version: 5.0.92
PHP version: 5.2.11With Prepared statements, you cannot use parameters just anywhere in any possible kind of query : it's not like a "put this into a string" : prepared statements depend on the server.
I suppose MySQL doesn't accept a parameter in a describe
query -- which explains the error.
You'll have to not use prepared statements, for this kind of query.
Quoting MySQL's documentation :
Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth.
In your case, you are trying to use a parameter marker for an identifier (a table's name) -- which is not supported.
精彩评论