Reputation: 3520
When using either bindParam or bindValue in PDO, where exactly is the "binding" stored in the PDOStatement object? Is it possible to display this set property/reference/etc.?
I'm trying to understand where these and other PDOStatement methods store/locate their data within a PDOStatement object (if it's even possible to access it outside of setting it through a PDOStatement method).
(I suppose this question extends to other PDO/PDOStatement methods, as well, curious where things are getting stored, like if into properties or whatnot)
Upvotes: 0
Views: 64
Reputation: 158100
A prepared statement is either a protocol feature (mysql for example) or will run in a C library behind the scenes. Meaning the work of parsing the statement isn't done by PDO code. It is done by the database server or a C library like libsqlite. As PDO doesn't parse the statement by itself and just passes it to the lower level component, param information isn't available to it.
So, using plain PHP it is not possible to get the association placeholder => replaced by value in query using the PDOStatement object. This is by design of a prepared statement.
A workaround might be to extend PDOStatement
and add a method that replaces param placeholders by their values in the current query string. I have prepared an example below. Note that this example isn't bullet-proof as it would for example replace :bar
even if it occurs in quoted strings. But for internal usage, a solution like this has done a good job for me so far.
Custom Statement Class:
class MyStatement extends PDOStatement
{
protected $params;
protected $pdo;
protected function __construct($pdo) {
$this->pdo = $pdo;
}
public function execute($params = null) {
$this->params = $params;
return parent::execute($params);
}
public function printQuery(){
$_params = $this->params;
$sql = $this->queryString;
foreach($this->params as $key => $value) {
$_value = is_null($value) ?
'NULL' : '\'' . $value . '\'';
$sql = str_replace(':'. $key, $_value, $sql);
}
return $sql;
}
}
class MyPDO extends PDO
{
public function __construct($dsn, $username="", $password="", $driver_options=array()) {
parent::__construct($dsn, $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STATEMENT_CLASS => array('MyStatement', array($this))
));
}
}
Test Code:
$pdo = new MyPDO('mysql:host=localhost;dbname=test', 'root', '******');
// preapre stupid query
$stmt = $pdo->prepare('SELECT FROM `foo` WHERE name = :bar');
try {
// execute stmt
$stmt->execute(array('bar' => 'hek2mgl'));
} catch (PDOException $e) {
echo $stmt->printQuery();
}
Upvotes: 1