This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 5 years ago.
On my server i get this error
Fatal error: Call to undefined method mysqli_stmt::get_result() in /var/www/virtual/fcb/htdocs/library/mysqlidbclass.php on line 144
And I am having a wrapper like this:
<?php
/* https://github.com/aaron-lord/mysqli */
class mysqlidb {
/**
* Set up the database connection
*/
public function __construct($server,$user,$password,$db){
$this->connection = $this->connect($server, $user, $password, $db, true);
}
/**
* Connect to the database, with or without a persistant connection
* #param String $host Mysql server hostname
* #param String $user Mysql username
* #param String $pass Mysql password
* #param String $db Database to use
* #param boolean $persistant Create a persistant connection
* #return Object Mysqli
*/
private function connect($host, $user, $pass, $db, $persistant = true){
$host = $persistant === true ? 'p:'.$host : $host;
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
throw new Exception('Connection Error: '.$mysqli->connect_error);
$mysqli->set_charset('utf8');
return $mysqli;
}
/**
* Execute an SQL statement for execution.
* #param String $sql An SQL query
* #return Object $this
*/
public function query($sql){
$this->num_rows = 0;
$this->affected_rows = -1;
if(is_object($this->connection)){
$stmt = $this->connection->query($sql);
# Affected rows has to go here for query :o
$this->affected_rows = $this->connection->affected_rows;
$this->stmt = $stmt;
return $this;
}
else {
throw new Exception;
}
}
/**
* Prepare an SQL statement
* #param String $sql An SQL query
* #return Object $this
*/
public function prepare($sql){
unset($this->stmt);
$this->num_rows = 0;
$this->affected_rows = -1;
if(is_object($this->connection)){
# Ready the stmt
$this->stmt = $this->connection->prepare($sql);
if (false===$this->stmt)
{
print('prepare failed: ' . htmlspecialchars($this->connection->error)."<br />");
}
return $this;
}
else {
throw new Exception();
}
}
public function multi_query(){ }
/**
* Escapes the arguments passed in and executes a prepared Query.
* #param Mixed $var The value to be bound to the first SQL ?
* #param Mixed $... Each subsequent value to be bound to ?
* #return Object $this
*/
public function execute(){
if(is_object($this->connection) && is_object($this->stmt)){
# Ready the params
if(count($args = func_get_args()) > 0){
$types = array();
$params = array();
foreach($args as $arg){
$types[] = is_int($arg) ? 'i' : (is_float($arg) ? 'd' : 's');
$params[] = $arg;
}
# Stick the types at the start of the params
array_unshift($params, implode($types));
# Call bind_param (avoiding the pass_by_reference crap)
call_user_func_array(
array($this->stmt, 'bind_param'),
$this->_pass_by_reference($params)
);
}
if($this->stmt->execute()){
# Affected rows to be run after execute for prepares
$this->affected_rows = $this->stmt->affected_rows;
return $this;
}
else {
throw new Exception($this->connection->error);
}
}
else {
throw new Exception;
}
}
/**
* Fetch all results as an array, the type of array depend on the $method passed through.
* #param string $method Optional perameter to indicate what type of array to return.'assoc' is the default and returns an accociative array, 'row' returns a numeric array and 'array' returns an array of both.
* #param boolean $close_stmt Optional perameter to indicate if the statement should be destroyed after execution.
* #return Array Array of database results
*/
public function results($method = 'assoc', $close_stmt = false){
if(is_object($this->stmt)){
$stmt_type = get_class($this->stmt);
# Grab the result prepare() & query()
switch($stmt_type){
case 'mysqli_stmt':
$result = $this->stmt->get_result();
$close_result = 'close';
break;
case 'mysqli_result':
$result = $this->stmt;
$close_result = 'free';
break;
default:
throw new Exception;
}
$this->num_rows = $result->num_rows;
# Set the results type
switch($method) {
case 'assoc':
$method = 'fetch_assoc';
break;
case 'row':
//return 'fetch_row';
$method = 'fetch_row';
break;
default:
$method = 'fetch_array';
break;
}
$results = array();
while($row = $result->$method()){
$results[] = $row;
}
$result->$close_result();
return $results;
}
else {
throw new Exception;
}
}
/**
* Turns off auto-committing database modifications, starting a new transaction.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function start_transaction(){
if(is_object($this->connection)){
return $this->connection->autocommit(false);
}
}
/**
* Commits the current transaction and turns auto-committing database modifications on, ending transactions.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function commit(){
if(is_object($this->connection)){
# Commit!
if($this->connection->commit()){
return $this->connection->autocommit(true);
}
else {
$this->connection->autocommit(true);
throw new Exception;
}
}
}
/**
* Rolls back current transaction and turns auto-committing database modifications on, ending transactions.
* #return bool Dependant on the how successful the autocommit() call was
*/
public function rollback(){
if(is_object($this->connection)){
# Commit!
if($this->connection->rollback()){
return $this->connection->autocommit(true);
}
else {
$this->connection->autocommit(true);
throw new Exception;
}
}
}
/**
* Return the number of rows in statements result set.
* #return integer The number of rows
*/
public function num_rows(){
return $this->num_rows;
}
/**
* Gets the number of affected rows in a previous MySQL operation.
* #return integer The affected rows
*/
public function affected_rows(){
return $this->affected_rows;
}
/**
* Returns the auto generated id used in the last query.
* #return integer The last auto generated id
*/
public function insert_id(){
if(is_object($this->connection)){
return $this->connection->insert_id;
}
}
/**
* Fixes the call_user_func_array & bind_param pass by reference crap.
* #param array $arr The array to be referenced
* #return array A referenced array
*/
private function _pass_by_reference(&$arr){
$refs = array();
foreach($arr as $key => $value){
$refs[$key] = &$arr[$key];
}
return $refs;
}
}
?>
Is there any way to use another function so that I won't have to rewrite whole app? Please tell me if any.
Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver. if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.fetch.php
Extracted from here
The reason for this error is that your server doesn't have the mysqlnd driver driver installed. (See here.) If you have admin privileges you could install it yourself, but there is also an easier way:
I have written two simple functions that give the same functionality as $stmt->get_result();, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result(); with $fields = bindAll($stmt);
and
$row= $stmt->get_result(); with $row = fetchRowAssoc($stmt, $fields);.
(To get the numbers of returned rows you can use $stmt->num_rows.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata(); function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!
Also posted here.
Related
I've been having trouble with storing a password_hash into my MySql database. It's cutting off characters from the beginning and some in between.
I've tried setting the encoding to UTF 8 in the HTML, setting the same in the connect function and also I've changed the collation to every possible type. Yet I am able to paste the correct hash from an echo into the database and that works fine.
$password = $_POST['pno'];
$pno = password_hash($password,PASSWORD_DEFAULT);
MySqlDb::query('INSERT INTO user (name, email, pno, address_line_1, address_line_2, town, county, post_code, phone) VALUES (:name, :email, :pno, :address_line_1, :address_line_2, :town, :county, :post_code, :phone)',
[':name'=>$name, ':email'=>$email, ':pno'=>$pno, ':address_line_1'=>$address_line_1, ':address_line_2'=>$address_line_2, ':town'=>$town, ':county'=>$county, ':post_code'=>$post_code, ':phone'=>$phone]);
echo $pno;
So the echo will give me this: $2y$10$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
But in the database it stores this:
y$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
I've also tried the encode and decode functions, pretty much out of ideas.
class MySqlDb {
/**
* #var MySQLi instance
*/
protected static $link;
/**
* #var bool set to true to print query before executing
*/
public static $debug = false;
/**
* Creates a new MySQLi instance use getConnection() to retrieve
* #return none
*/
private function __construct() {
self::$link = #mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);
if (mysqli_connect_errno()) {
//die('MySqlDb Error: Could not connect to database ('.mysqli_connect_errno().')');
throw new Exception('MySqlDb::() Could not connect to database (' . mysqli_connect_errno() . ')');
}
}
/**
* Returns the MySQLi connection
* #return MySQLi instance
*/
public static function getConnection() {
if (!self::$link) {
new MySqlDb();
}
return self::$link;
}
/**
* Helper function for mysqli_query if params are given will use quote function
* see below MySqlDb:quote this is to help avoid sql injection attacks and automatically escape slashes etc
*
* #param string $sql
* #param array $params
* #return mysqli_query resource ...
*
* Example:
* MySqlDb::query("drop from user where id=$_GET['id']"); // very bad 'id' could contain "' or 1=1"
* MySqlDb::query("drop from user where id=:id", [':id' => $_GET['id']]); // much better
*/
public static function query($sql, array $params = null) {
$con = self::getConnection();
if (!empty($params)) {
$sql = self::quote($sql, $params);
}
if (self::$debug) {
echo $sql;
}
$res = mysqli_query($con, $sql);
if (!$res) {
//die('MySqlDb Error: query: '.mysqli_error($con));
throw new Exception('MySqlDb::query() ' . mysqli_error($con));
}
return $res;
}
/**
* Helper function to quote sql values similar to pdo::bindvalue using named parameters
* to help avoid sql injection attacks and avoid using stuff like addslashes
*
* #param string $sql sql string to quote
* #param array $params key value pairs of parameters and values to placed into them
* #return string sql quoted string
*
* Example:
* $sql = MySqlDb::quote("select * from users where id=:unique1 or id=:unique2", [':unique1'=>2, ':unique2'=>4])
* TODO:
* MySqlDb::quote("select * from users where id+5 = :id or id = :id",[':id'=>3] fails on number params dont match like pdo
* could convert 'substr_count($sql, ':')' into '$unique_sql_param_count'
* e.g. preg_match_all("/:[\w-_]+\b/i", $test, $matches); $paramcount = count(array_flip($matches[0]));
*/
public static function quote($sql, array $params) {
// check correct number of params
if (substr_count($sql, ':') != count($params)) {
//die('MySqlDb Error: quote: number params do not match');
throw new Exception('MySqlDb::quote() number params do not match');
}
$cnt = 0;
foreach ($params as $param => $value) {
//$sql = str_replace($param, "'".self::escape($value)."'", $sql, $cnt); // was matching sub strings :(
$sql = preg_replace("/$param\b/i", "'" . self::escape($value) . "'", $sql, -1, $cnt);
if ($cnt !== 1) {
//die("MySqlDb Error: quote: param '{$param}' not matched or is duplicate");
throw new Exception("MySqlDb::quote() param '{$param}' not matched or is duplicate");
}
}
return $sql;
}
/**
* Wrapper for mysqli_escape_string
* #param mixed $value
* #return escaped value
*/
public static function escape($value) {
return mysqli_escape_string(self::getConnection(), $value);
}
/**
* Helper function to return all rows in result as an associative array
* #param string $sql
* #return array array of arrays
*/
public static function all($sql, array $params = null) {
return mysqli_fetch_all(self::query($sql, $params), MYSQLI_ASSOC);
}
/**
* Helper function to return first row in result from potential multiple values
* #param string $sql
* #return array single array
*/
public static function first($sql, array $params = null) {
$res = mysqli_fetch_array(self::query($sql, $params), MYSQLI_ASSOC);
return is_array($res) ? $res : [];
}
/**
* Helper function to return first field in result from potential multiple values
* #param string $sql
* #return mixed single variable
*/
public static function scalar($sql, array $params = null) {
$res = mysqli_fetch_array(self::query($sql, $params), MYSQLI_NUM);
return is_array($res) ? $res[0] : null;
}
}
This line in your quote method is the direct cause of the problem.
$sql = preg_replace("/$param\b/i", "'" . self::escape($value) . "'", $sql, -1, $cnt);
The result of self::escape($value) will be your original hash,
$2y$10$rtlUaDeXsyhtWS5.SS4nuu.xapBdrHXG7V.DpSLCLAAwYqXPJHKWi
In the context of preg_replace, the $2 and $10 are meaningful. In the Parameters section of the preg_replace documentation it says
replacement may contain references of the form \n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern.
You have no parenthesized patterns, so those values are replaced with nothing.
You could fix it by escaping any $ in the replacement parameter, but I would rather recommend replacing your escape/replace-based quote method with a method that creates a prepared statement and binds the parameters before executing it.
I am trying to write my own MVC Framework using this tutorial. Everything worked fine and i completed the tutorial with no issues.
However later i decided to use PDO (PHP Data objects) instead of mysql() functions for Database Operations. So i modified My sqlQuery.php file to use PDO istead of mysql functions.
sqlQuery.php
<?php
class SQLQuery {
private $_dbHandle;
private $_result;
/**
* Connects to database
*
* #param $address
* #param $account
* #param $pwd
* #param $name
*/
function connect($address, $account, $pwd, $name) {
try{
$this->_dbHandle = new PDO("mysql:host=$address;dbname=$name", $account, $pwd);
}catch (PDOException $e) {
die($e->getCode() . " : " . $e->getMessage());
}
}
/** Disconnects from database **/
function disconnect() {
$this->_dbHandle = null;
}
function get($whereClause = array()) {
$query = "select * from $this->_table";
if(is_array($whereClause) && count($whereClause)){
$query .= " where ";
foreach($whereClause as $column=>$value)
$query .= " $column = $value";
}else if(is_int($whereClause)){
$query .= " where id = $whereClause ";
}
return $this->query($query);
}
/**
* Custom SQL Query
*
* #param $query
* #return array|bool
*/
function query($query) {
$this->_result = $this->_dbHandle->query($query);
$this->_result->setFetchMode(PDO::FETCH_CLASS, $this->_model);
if (preg_match("/select/i",$query)) {
$result = array();
$numOfFields = $this->_result->rowCount();
if($numOfFields > 1){
while($result[] = $this->_result->fetch()){
}
}else{
$result = $this->_result->fetch();
}
return $result;
}
return true;
}
}
Now when In my Controller when i print $this->Item->get() I get all the results in my database as Objects of Items Model and $this->Item->get(2) gives me the item object with id=2 as expected.
However, I don't like the idea that my API needs to be to call an additional method get() to get the objects of the Items Model, Instead it makes more sense that when a Items Model is initialized i get the desired object and so my API can be $this->item->mycolumnName.
To achieve this i tried to move the get() call in the Models constructor like this :
model.php
<?php
class Model extends SQLQuery{
protected $_model;
function __construct() {
$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
$this->get();
}
function __destruct() {
}
}
However this gives me a Fatal error
Fatal error: Maximum function nesting level of '256' reached, aborting! in /var/www/html/FitternityAssignment/library/sqlquery.php on line 59
I don't know what i have done wrong.
The issue is line 59: while($result[] = $this->_result->fetch()){
function query($query) {
$this->_result = $this->_dbHandle->query($query);
$this->_result->setFetchMode(PDO::FETCH_CLASS, $this->_model);
if (preg_match("/select/i",$query)) {
$result = array();
$numOfFields = $this->_result->rowCount();
if($numOfFields > 1){
while($result[] = $this->_result->fetch()){
}
}else{
$result = $this->_result->fetch();
}
return $result;
}
return true;
}
Let's narrow in on the issue:
while($result[] = $this->_result->fetch()){
}
Infinite loop.
When fetch() returns something, then it is added to $result, because $result is an array, and then of course it evaluates to true because the size of $result grows each time a fetched result is added.
$results = [];
while($row = $this->_result->fetch()){
$results[] = $row; // or whatever you need to do with the row
}
Might work. I say might because it depends on what $this->_result->fetch() returns when no results are left. I'll assume false or null, in which case the above will work, because when there are no more results then fetch() will return null or false and $row will then evaluate to false.
I want to view the SQL statement that is about to be executed below :
<?php
//Deleting existing robot
$success = $connection->delete(
"robots",
"id = 101"
);
//Next SQL sentence is generated
DELETE FROM `robots` WHERE `id` = 101
How can I add some kind of listener or just plain var_dump the select query that is about to generated by the $connection->delete
Thanks
The way I settled on is to use a logger class and the event system: Phalcon Events Manager
You create a class that extends the logger adapter
<?php
namespace PhalconX\Logger\Adapter;
/**
* Basic Array based Logging for debugging Phalcon Operations
* #package PhalconX\Logger\Adapter
*/
class Basic extends \Phalcon\Logger\Adapter
{
private $data = array();
/**
* Add a statement to the log
* #param string $statement
* #param null $type
* #param array $params
* #return $this|\Phalcon\Logger\Adapter
*/
public function log($statement, $type=null, array $params=null)
{
$this->data[] = array('sql'=>$statement, 'type'=>$type, 'params'=>$params); // array('sql'=>$statement, 'type'=>$type);
return $this;
}
/**
* return the log
* #return array
*/
public function getLog(){
return $this->data;
}
/**
* Required function for the interface, unused
* #param $message
* #param $type
* #param $time
* #param $context
*/
public function logInternal($message, $type, $time, $context){
}
/**
* Required function for the interface, unused
*/
public function getFormatter(){
}
/**
* Required function for the interface, unused
*/
public function close(){
}
}
and then attach it to your database, and plumb in the events by type
$eventsManager = new \Phalcon\Events\Manager();
$logger = new \PhalconX\Logger\Adapter\Basic();
$profiler = $phalconDi->getProfiler();
//Listen all the database events
/** #var $event \Phalcon\Events\Event */
/** #var $phalconConnection \Phalcon\Db\Adapter\Pdo\Mysql */
$eventsManager->attach('db', function($event, $phalconConnection) use ($logger, $profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($phalconConnection->getSQLStatement());
$logger->log($phalconConnection->getSQLStatement(), \Phalcon\Logger::INFO, $phalconConnection->getSQLVariables());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
This presumes you have a 'db' key in your dependency injector.
My logger just stores the queries in an array so I can output them at the bottom of my page.
My trick to factor a closest to real SQL statement out of those prepared ones:
function statement2sql($connection) {
$stmt = $connection->getSQLStatement();
foreach ( $connection->getSQLVariables() as $k => $v ) {
// replaces :p1, .. :p11 .. and defined binds with binded values
$stmt = preg_replace('/:' . $k . '([^A-Za-z0-9])/', '\'' . $v . '\'$1', $stmt);
}
return $stmt;
}
Defined as method or function, you can push its result to profiler as in accepted answer:
$eventsManager->attach('db:beforeQuery', function($event, $connection) {
$profiler->startProfile(statement2sql($connection));
}
$eventsManager->attach('db:afterQuery', function($event, $connection) {
$profiler->stopProfile();
}
or store in other way - using logger or other debugging class.
I've had good luck wrapping my SQL execute call in a try/catch, then printing the exception. Any error message returned by MySQL is in the exception's message, which will contain the raw query.
function get_item_by_id ($db_connection, $item_id) {
try {
$stmt = 'SELECT * FROM inventory WHERE id=:id';
$prepared_stmt = $db_connection->prepare ($stmt);
$result = $db_connection->executePrepared ($prepared_stmt,
array (
"id" => $item_id
),
array (
"id" => Column::BIND_PARAM_INT
)
);
$result->setFetchMode (Phalcon\Db::FETCH_OBJ);
$item_arr = $result->fetchAll ();
return $item_arr;
}
catch (Exception $e) {
print_r ($e->getMessage());
}
}
Another option, my personal preference, is to look at the situation from the perspective of the database. Most SQL databases allow you to set a trigger for certain events (in your case, DELETE), and generate a log entry with the full text of the incoming request.
Reference: https://stackoverflow.com/a/10671410/1504367.
Doctrine 2 has the Doctrine\ORM\Tools\Pagination\Paginator class which can be used to paginate normal DQL queries.
However if I pass it a native query, I get this error:
Catchable fatal error: Argument 1 passed to Doctrine\ORM\Tools\Pagination\Paginator::cloneQuery() must be an instance of Doctrine\ORM\Query, instance of Doctrine\ORM\NativeQuery given
I've tried removing the type-hinting from the paginator class in the cloneQuery method, but this just gives further errors because other bits of the paginator class expect methods found in Query that aren't in NativeQuery.
Is there any easy way of paginating the native queries without needing to build a new paginator class or fetching every row from the database into an array?
I made my own paginator adapter class compatible with Zend_Paginator.
Probably won't be the most flexible since it relies on there being a " FROM " near the start of the query (see the count() method) but it's a relatively quick and easy fix.
/**
* Paginate native doctrine 2 queries
*/
class NativePaginator implements Zend_Paginator_Adapter_Interface
{
/**
* #var Doctrine\ORM\NativeQuery
*/
protected $query;
protected $count;
/**
* #param Doctrine\ORM\NativeQuery $query
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the total number of rows in the result set.
*
* #return integer
*/
public function count()
{
if(!$this->count)
{
//change to a count query by changing the bit before the FROM
$sql = explode(' FROM ', $this->query->getSql());
$sql[0] = 'SELECT COUNT(*)';
$sql = implode(' FROM ', $sql);
$db = $this->query->getEntityManager()->getConnection();
$this->count = (int) $db->fetchColumn($sql, $this->query->getParameters());
}
return $this->count;
}
/**
* Returns an collection of items for a page.
*
* #param integer $offset Page offset
* #param integer $itemCountPerPage Number of items per page
* #return array
*/
public function getItems($offset, $itemCountPerPage)
{
$cloneQuery = clone $this->query;
$cloneQuery->setParameters($this->query->getParameters(), $this->query->getParameterTypes());
foreach($this->query->getHints() as $name => $value)
{
$cloneQuery->setHint($name, $value);
}
//add on limit and offset
$sql = $cloneQuery->getSQL();
$sql .= " LIMIT $itemCountPerPage OFFSET $offset";
$cloneQuery->setSQL($sql);
return $cloneQuery->getResult();
}
}
public function countTotalRecords($query, string $primaryKey = '*'): int
{
if ($query instanceof QueryBuilder) {
$paginator = new Paginator($query->getQuery());
return count($paginator);
} else if ($query instanceof NativeQuery) {
$rsm = new ResultSetMappingBuilder($query->getEntityManager());
$rsm->addScalarResult('count', 'count');
$sqlCount = "select count(".$primaryKey.") as count from (" . $query->getSQL() . ") as item";
$count = $query->getEntityManager()->createNativeQuery($sqlCount, $rsm);
if ($query->getParameter('limit')) {
$query->setParameter('limit', null);
}
$count->setParameters($query->getParameters());
return (int)$count->getSingleScalarResult();
}
return 0;
}
If you have a dbal query builder that you have constructed with
$yourDbalQueryBuilder = $connection->createQueryBuilder();
then you can use:
$yourDbalQueryBuilder->setFirstResult(0)
->setMaxResults(100000000)
->execute()
->rowCount();
I am trying to make an intermediate class which will log the queries in an array along with their execution time. Everything is fine and it works perfectly. But autocomplete doesnt work when i try to access the intermediate class. How can get the autocomplete to work. I am using Netbeans.
Intermediate classname is Model.
From my application, i have a class by the name Users which extends Model.
class Users extends Model
{
function __construct() {
parent::__construct();
$stmt = $this->prepare('SELECT * FROM users WHERE id=? ');
$stmt->bindValue(1, 1); //$stmt-> auto-complete is unavailable
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($rows); //i get results
}
}
My Model class looks like this.
class Model extends PDO
{
public static $log = array();
private $query_cache = array();
public function __construct() {
parent::__construct(
"mysql:dbname=".MYSQL_DB.";host=".MYSQL_HOST,
MYSQL_USER, MYSQL_PASSWORD
);
}
public function query($query) {
$time = "";
$query = mysql_real_escape_string(preg_replace( '/\s+/', ' ', $query ));
if (key_exists($query,$this->query_cache)
&& is_object($this->query_cache[$query]))
{
$result = $this->query_cache[$query];
} else {
$start = microtime(true);
$result = parent::query($query);
$time = microtime(true) - $start;
$this->query_cache[$query] = $result;
Logger::$logText['DATABASE'][] = array(
'QUERY' => $query,
'TIME' => number_format($time,4)
);
}
return $result;
}
/**
* #return LoggedPDOStatement
*/
public function prepare($query) {
return new LoggedPDOStatement(parent::prepare($query));
}
}
My LoggedPDOStatement looks like this.
class LoggedPDOStatement
{
/**
* The PDOStatement we decorate
*/
private $statement;
public function __construct(PDOStatement $statement) {
$this->statement = $statement;
}
/**
* When execute is called record the time it takes and
* then log the query
* #return PDO result set
*/
public function execute() {
$start = microtime(true);
$result = $this->statement->execute();
$time = microtime(true) - $start;
Model::$log[] = array(
'query' => '[PS] ' . $this->statement->queryString,
'time' => round($time * 1000, 3)
);
return $result;
}
/**
* Other than execute pass all other calls to the PDOStatement object
* #param string $function_name
* #param array $parameters arguments
*/
public function __call($function_name, $parameters) {
return call_user_func_array(
array($this->statement, $function_name), $parameters
);
}
}
Is their any better way of doing this ?
I have fixed this taking suggestions from #cillosis and #Touki
#Touki, i agree i shouldnt extend the PDO Class.
#cillosis, thanks for your comments.
This is the way i have written my class. I have not pasted the full code as its not complete yet. But i have checked it works. And i can log my queries as well. However i am not sure if i will be able to log the execution time.
class Model
{
/**
* The singleton instance
*
*/
static private $PDOInstance;
public function __construct($dsn="", $username = false, $password = false, $driver_options = false) {
if (!self::$PDOInstance) {
try {
self::$PDOInstance = new PDO(
"mysql:dbname=".MYSQL_DB.";host=".MYSQL_HOST,
MYSQL_USER, MYSQL_PASSWORD
);
} catch (PDOException $e) {
die("PDO CONNECTION ERROR: " . $e->getMessage() . "<br/>");
}
}
return self::$PDOInstance;
}
/**
* Initiates a transaction
*
* #return bool
*/
public function beginTransaction() {
return self::$PDOInstance->beginTransaction();
}
public function prepare($statement, $driver_options = false) {
//log the $statement
if (!$driver_options)
$driver_options = array();
return self::$PDOInstance->prepare($statement, $driver_options);
}
}