Don't try to use PDO as a fluent interface. You can't do this:
$db->prepare()->execute();
The reason is that fluent interfaces work only if the function is guaranteed to return an object that has in this case an execute method.
But prepare() returns false
on error. The value false
isn't an object, and doesn't have an execute() method.
You need to check for false
after every prepare() and after every execute():
$stmt = $this->db->prepare("select :val from :table_name where username = :username");
if ($stmt === false) {
$err = $this->db->errorInfo();
error_log($err[2]);
}
$result = $stmt->execute(array(':username'=>$username,':val'=>$val,':table_name'=>$this->table_name));
if ($result === false) {
$err = $stmt->errorInfo();
error_log($err[2]);
}
If you do this, you'll find that an error was reported on your prepare():
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user' where username = 'bill'' at line 1
The reason is that query parameters are only for constant values. You can't use them for table names, column names, SQL keywords, expressions, lists of values, etc.
I'm inferring that :val
is also meant to be a dynamic column name, and that's not allowed either. But in that case, it won't result in an error, it'll just substitute a literal string with the value of $val
for every row returned.
In other words, substituting the table name with a parameter is wrong because you can't do a query like SELECT * FROM 'user'
(literal string, not table name), and that's how the parameter will act. It's simply invalid SQL.
But the dynamic column name will do a query like SELECT 'val' FROM ...
and that's legal, but won't select from the column named val, it'll select the literal string constant 'val'.