This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I keep getting the following error:
Fatal error: Call to a member function execute() on null in /home/[sitename]/public_html/fc/includes/class_db_handle.php on line 130
This is from the u-Auctions script and I honestly am extremely noob to PDO
please help in "DUMMIE TERMS".
if (!defined('InuAuctions')) exit('Access denied');
class db_handle
{
// database
private $pdo;
private $DBPrefix;
private $CHARSET;
private $lastquery;
private $fetchquery;
private $error;
public $PDOerror;
public function connect($DbHost, $DbUser, $DbPassword, $DbDatabase, $DBPrefix, $CHARSET)
{
$this->DBPrefix = $DBPrefix;
$this->CHARSET = $CHARSET;
try {
// MySQL with PDO_MYSQL
$this->pdo = new PDO("mysql:host=$DbHost;dbname=$DbDatabase;charset =$CHARSET", $DbUser, $DbPassword);
// set error reporting up
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// actually use prepared statements
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
// to run a direct query
public function direct_query($query)
{
try {
$this->lastquery = $this->pdo->query($query);
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
// put together the quert ready for running
/*
$query must be given like SELECT * FROM table WHERE this = :that AND where = :here
then $params would holds the values for :that and :here, $table would hold the vlue for :table
$params = array(
array(':that', 'that value', PDO::PARAM_STR),
array(':here', 'here value', PDO::PARAM_INT),
);
last value can be left blank more info http://php.net/manual/en/pdostatement.bindparam.php
*/
public function query($query, $params = array())
{
try {
//$query = $this->build_query($query, $table);
$params = $this->build_params($params);
$params = $this->clean_params($query, $params);
$this->lastquery = $this->pdo->prepare($query);
//$this->lastquery->bindParam(':table', $this->DBPrefix . $table, PDO::PARAM_STR); // must always be set
foreach ($params as $val)
{
$this->lastquery->bindParam($val[0], $val[1], #$val[2], #$val[3], #$val[4]);
}
$this->lasta->execute();
//$this->lastquery->debugDumpParams();
}
catch(PDOException $e) {
//$this->lastquery->debugDumpParams();
$this->trigger_error($e->getMessage());
}
//$this->lastquery->rowCount(); // rows affected
}
// put together the quert ready for running
public function fetch($method = 'FETCH_ASSOC')
{
try {
// set fetchquery
if ($this->fetchquery == NULL)
{
$this->fetchquery = $this->lastquery;
}
if ($method == 'FETCH_ASSOC') $result = $this->fetchquery->fetch(PDO::FETCH_ASSOC);
if ($method == 'FETCH_BOTH') $result = $this->fetchquery->fetch(PDO::FETCH_BOTH);
if ($method == 'FETCH_NUM') $result = $this->fetchquery->fetch(PDO::FETCH_NUM);
// clear fetch query
if ($result == false)
{
$this->fetchquery = NULL;
}
return $result;
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
// put together the quert ready for running + get all results
public function fetchall($method = 'FETCH_ASSOC')
{
try {
// set fetchquery
if ($this->fetchquery == NULL)
{
$this->fetchquery = $this->lastquery;
}
if ($method == 'FETCH_ASSOC') $result = $this->fetchquery->fetchAll(PDO::FETCH_ASSOC);
if ($method == 'FETCH_BOTH') $result = $this->fetchquery->fetchAll(PDO::FETCH_BOTH);
if ($method == 'FETCH_NUM') $result = $this->fetchquery->fetchAll(PDO::FETCH_NUM);
// clear fetch query
if ($result == false)
{
$this->fetchquery = NULL;
}
return $result;
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
public function result($column = NULL)
{
$data = $this->lastquery->fetch(PDO::FETCH_BOTH);
if (empty($column) || $column == NULL)
{
return $data;
}
else
{
return $data[$column];
}
}
public function numrows()
{
try {
return $this->lastquery->rowCount();
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
public function lastInsertId()
{
try {
return $this->pdo->lastInsertId();
}
catch(PDOException $e) {
$this->trigger_error($e->getMessage());
}
}
private function clean_params($query, $params)
{
// find the vars set in the query
preg_match_all("(:[a-zA-Z_]+)", $query, $set_params);
//print_r("params" . $query);
//print_r($params);
//print_r("set_params");
//print_r($set_params);
$new_params = array();
foreach ($set_params[0] as $val)
{
$key = $this->find_key($params, $val);
$new_params[] = $params[$key];
}
//print_r("new_params");
//print_r($new_params);
return $new_params;
}
private function find_key($params, $val)
{
foreach ($params as $k => $v)
{
if ($v[0] == $val)
return $k;
}
}
private function build_params($params)
{
$PDO_constants = array(
'int' => PDO::PARAM_INT,
'str' => PDO::PARAM_STR,
'bool' => PDO::PARAM_BOOL,
'float' => PDO::PARAM_STR
);
// set PDO values to params
for ($i = 0; $i < count($params); $i++)
{
// force float
if ($params[$i][2] == 'float')
{
$params[$i][1] = floatval($params[$i][1]);
}
$params[$i][2] = $PDO_constants[$params[$i][2]];
}
return $params;
}
private function trigger_error($error)
{
// DO SOMETHING
//$this->error = $error;
$this->PDOerror = $error;
}
// close everything down
public function __destruct()
{
// close database connection
$this->pdo = null;
}
}
You call $this->lasta->execute(); but you have no field lasta
Try this
$this->lastquery->execute();
I would try extending the db_handle class and modifying/creating some methods like so:
<?php
// Make sure the db_handle is included and loaded before hand so it can be extended
class QueryEngine extends db_handle
{
private $bind;
public function connect($host, $username, $password, $database)
{
// One note, I removed:
// $this->DBPrefix = $DBPrefix;
// $this->CHARSET = $CHARSET;
// You can add those back in if you want
try {
// Create connection
$opts = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$this->pdo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password,$opts);
}
catch(PDOException $e) {
die($e->getMessage());
}
}
public function query($query, $params = false)
{
if(!empty($params))
$this->bindVals($params);
try {
if(!empty($this->bind)) {
$this->lastquery = $this->pdo->prepare($query);
$this->lastquery->execute($this->bind);
}
else
$this->lastquery = $this->pdo->query($query);
}
catch(PDOException $e) {
die($e->getMessage());
}
return $this;
}
public function fetch()
{
while($row = $this->lastquery->fetch())
$result[] = $row;
return (!empty($result))? $result : 0;
}
private function bindVals($params = false)
{
$this->bind = false;
if(empty($params) || !is_array($params))
return $this;
$i = 0;
foreach($params as $values) {
$this->bind[':'.$i] = $values;
$i++;
}
return $this;
}
}
To use our new class:
$dbEngine = new QueryEngine();
$dbEngine->connect($host,$username,$password,$database);
print_r($dbEngine->query("select * from users where ID = :0",array("1"))->fetch());
This would give you something like (in my db obviously, the table and columns will be different for you):
Array
(
[0] => Array
(
[ID] => 1
[unique_id] => 20150203190700523616
[username] => tester
[password] => $2a$12$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[first_name] => Ras
[last_name] => Clatt
[email] => ras#clatt.com
[usergroup] => 3
[user_status] => on
[reset_password] => $2y$10$xxxxxxxxxxxxxxxxxxx
[timestamp] => 2015-09-25 08:35:09
)
)
This class library you are using is similar to mine so what I have added is parts of the class I use. I tested this extended class out and it works with my database, so hopefully it works with yours!
Related
This has nothing to do with Frameworks because it is an external project, I am currently developing to learn, some things about database management or how databases behave...
I need help with some php and PDO... Previously I dev this script:
<?php
class DataBaseManager
{
public function GetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8");
reset($query);
$db_name = key($query);
$conn->exec('USE ' . $db_name);
$db_result['r'] = $conn->query($query[$db_name], PDO::FETCH_ASSOC);
$count = $db_result['r']->rowCount();
$db_result['c'] = $count;
if (0 == $count) {
$db_result['r'] = null;
} elseif (1 == $count) {
$db_result['r'] = $db_result['r']->fetch();
}
return $db_result;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
public function DeleteData($query, $user, $pass)
{
try {
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$conn->exec($query_string);
++$ct;
}
}
$conn->commit();
$conn = null;
return '<b>' . $ct . ' Records Deleted Successfully.</b>';
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
public function SetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
$count = ['u' => 0, 'i' => 0];
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$cq = $conn->exec($query_string);
if (strpos($query_string, 'UPDATE') !== false) {
$count['u'] += $cq;
}
if (strpos($query_string, 'INSERT') !== false) {
$count['i'] += $cq;
}
}
}
$conn->commit();
$db_result['r'] = true;
$db_result['t'] = 'Updates: ' . $count['u'] . ', Inserts: ' . $count['i'];
return $db_result;
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
}
I would like to be able to insert data by volumes in multiple tables in a single commit...
The idea of doing it that way is because if something fails I want it to be automatically rolled back in all table instances...
So I have a data structure in an array with the following content in my new class:
$dbquery =[
'test'=>[
'0' =>[
0 => 'INSERT INTO table_name_1(column1,column2) VALUES (?,?)', //mean it is the query
1 =>[value11,value12], // mean it is a row
2 =>[value21,value22], // mean it is a row
],
'1' =>[
0 => 'INSERT INTO table_name_2(column1,column2,column3,column4) VALUES (?,?,?,?)', //mean it is the query
1 =>[value11,value12,value13,value14], // mean it is a row
2 =>[value21,value22,value23,value24], // mean it is a row
],
],
];
but i have my first try with bindValue, this is my new class mentioned:
<?php
class DataBase
{
private static ?DataBase $instance = null;
public static function getInstance(): DataBase
{
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
private array $config;
public function __construct()
{
$this->config = ['DB_HOST'=>'test','DB_NAME'=>'test','DB_USER'=>'test','DB_PASSWORD'=>''];
$this->setConnection(new PDO("mysql:host=" . $this->config['DB_HOST'] . ";dbname=" . $this->config['DB_NAME'], $this->config['DB_USER'], $this->config['DB_PASSWORD']));
}
private PDO $connection;
/**
* #return PDO
*/
private function getConnection(): PDO
{
return $this->connection;
}
/**
* #param PDO $connection
*/
private function setConnection(PDO $connection): void
{
$this->connection = $connection;
}
public function changeConnectionServer(string $host, string $db_name, string $user, string $password): void
{
$this->setConnection(new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $user, $password));
}
private array $query;
public function setDataBaseTarget(string $db_name)
{
if (empty($this->query)) {
$this->query = [];
}
$this->query[$db_name] = [];
}
public function buildQuery(string $query)
{
if (empty($this->query)) {
$this->query = [];
$this->query[$this->config['DB_NAME']] = [];
}
$target = array_key_last($this->query);
$this->query[$target][] = [$query];
}
public function addQueryData($data)
{
$target = array_key_last($this->query);
$key = array_key_last($this->query[$target]);
$this->query[$target][$key][] = $data;
}
private function getQuery(): array
{
return $this->query;
}
/**
* #throws Exception
*/
public function setData(): array
{
try {
$time = -microtime(true);
$con = $this->getConnection();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$con->exec("set names utf8;");
foreach ($this->getQuery() as $db_name => $query_arr) {
$con->exec('USE `' . $db_name . '`;');
$ct = 0;
// on this section have proble with code and logic .... i dont know what i need to dev to insert the data
foreach ($query_arr as $query_structure) {
foreach ($query_structure as $key => $raw) {
if ($key === 0) {
$ct++;
$stmt[$ct] = $con->prepare($raw);
} else {
if (is_array($raw)) {
$c = 0;
foreach ($raw as $value) {
$c++;
$stmt[$ct]->bindValue($c, $value, $this->getParamType($value));
}
}
}
}
$stmt[$ct]->execute();
}
//end section
}
//$con->commit();
return true;
} catch (PDOException $e) {
$con->rollback();
echo $e->getMessage();
return false;
}
}
private function getParamType($value)
{
if (is_int($value)) {
return PDO::PARAM_INT;
} elseif (is_bool($value)) {
return PDO::PARAM_BOOL;
} elseif (is_null($value)) {
return PDO::PARAM_NULL;
} elseif (is_string($value)) {
return PDO::PARAM_STR;
} else {
return false;
}
}
}
$db_handler = DataBase::getInstance();
$db_handler->buildQuery("INSERT INTO `client_list`(`email`,`mobile`) VALUES ('?','?');");
$db_handler->addQueryData(['mail1#test.com', '35634634636546']);
$db_handler->addQueryData(['mail2#test.com', '35634634636546']);
$db_handler->addQueryData(['mail3#test.com', '35634634636546']);
$db_handler->setData();
I can't figure out, develop the part that allows me to package everything in a single transaction... what I have is a stm[] ...
Can someone help me with this development?
I can't make heads or tails of all the things your class is doing, but here's a generalized version according to the bits that seem obvious:
public function runMultipleQueries() {
$dbh = $this->getConnection();
// ... setup stuff
$dbh->beginTransaction();
try {
foreach($this->queries as $query) {
$stmt->prepare($query->queryString);
$param_id = 1;
foreach($query->params as $param) {
$stmt->bindValue($param_id++, $param);
}
$stmt->execute();
}
} catch( \Exception $e ) {
$dbh->rollback();
throw $e;
// IMO if you cannot fully/meaningfully recover, just re-throw and let it kill execution or be caught elsewhere where it can be
// otherwise you're likely having to maintain a stack of if(foo() == false) { ... } wrappers
}
$dbh->commit();
}
Additionally, singleton DB classes have the drawbacks of both being limiting if you ever need a second DB handle, as well as boiling down to being global state, and subject to the same "spooky action at a distance" problems.
Consider using dependency inversion and feeding class dependencies in via constructor arguments, method dependencies via method arguments, etc. Eg:
interface MyWrapperInterface {
function setQueries(array $queries);
function runQueries();
}
class MyDbWrapper implements MyWrapperInterface {
protected $dbh;
public function __construct(\PDO $dbh) {
$this->dbh = $dbh;
}
public function setQueries(array $queries) { /* ... */ }
public function runQueries() { /* ... */ }
}
class MyOtherThing {
protected $db;
public function __construct( MyWrapperInterface $db ) {
$this->db = $db;
}
// ...
}
$wrapper1 = new MyDbWrapper(new PDO($connstr1, $options));
$wrapper2 = new MyDbWrapper(new PDO($connstr2, $options));
$thing1 = new MyOtherThing($wrapper1);
$thing2 = new MyOtherThing($wrapper2);
$thing1_2 = new MyOtherThing($wrapper1);
// etc
I have problem with save data in mysql.
I have such a class to connect with databases:
class Db
{
private $_hostname;
private $_database;
private $_username;
private $_password;
private $_port;
private $_pdo;
private $_sQuery;
private $_bConnected = false;
private $_parameters;
private $_config;
private $_psException;
public function __construct()
{
$this->_config = Registry::register("Core\Utilities\Config");
$this->_psException = new PsException();
$this->_hostname = $this->_config->db_host;
$this->_database = $this->_config->db_db;
$this->_username = $this->_config->db_user;
$this->_password = $this->_config->db_pass;
$this->_port = $this->_config->db_port;
$this->Connect($this->_hostname, $this->_database, $this->_username, $this->_password, $this->_port);
$this->_parameters = array();
}
private function Connect($hostname, $database, $username, $password, $port)
{
try {
$options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'");
$this->_pdo = new \PDO("mysql:host={$hostname};dbname={$database};port={$port};charset=utf8", $username, $password, $options);
$this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$this->_pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
$this->_pdo->query('SET NAMES utf8');
$this->_bConnected = true;
} catch (PDOException $ex) {
$this->_psException->registerError("Failed to connect to the database: " . $ex->getMessage());
} catch (Exception $e) {
$this->_psException->registerError("Failed to connect to the database: " . $e->getCode() . "." . $e->getMessage());
}
}
public function CloseConnection()
{
$this->_pdo = null;
}
private function Init($query, $parameters = "")
{
if (!$this->_bConnected) {
$this->Connect();
}
try {
$this->_sQuery = $this->_pdo->prepare($query);
$this->bindMore($parameters);
if (!empty($this->_parameters)) {
foreach ($this->_parameters as $param) {
$parameters = explode("\x7F", $param);
$this->_sQuery->bindParam($parameters[0], $parameters[1]);
}
}
$this->success = $this->_sQuery->execute();
} catch (PDOException $e) {
$this->ExceptionLog($e->getMessage(), $query);
}
$this->_parameters = array();
}
public function bind($para, $value)
{
$this->_parameters[sizeof($this->_parameters)] = ":" . $para . "\x7F" . ($value);
}
public function bindMore($parray)
{
if (empty($this->_parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function query($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$query = trim($query);
$this->Init($query, $params);
$rawStatement = explode(" ", $query);
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->_sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->_sQuery->rowCount();
} else {
return null;
}
}
public function lastInsertId()
{
return $this->_pdo->lastInsertId();
}
public function column($query, $params = null)
{
$this->Init($query, $params);
$Columns = $this->_sQuery->fetchAll(\PDO::FETCH_NUM);
$column = null;
foreach ($Columns as $cells) {
$column[] = $cells[0];
}
return $column;
}
public function row($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$this->Init($query, $params);
return $this->_sQuery->fetch($fetchmode);
}
public function single($query, $params = null)
{
$this->Init($query, $params);
return $this->_sQuery->fetchColumn();
}
private function ExceptionLog($message, $sql = "")
{
$message .= 'Unhandled Exception. $message';
if (!empty($sql)) {
$message .= "\r\nQuery SQL : " . $sql;
}
$this->_psException->registerError($message);
}
}
and the method to write:
$queryValue["enable"] = $dataValues['enable'];
$queryValue["number"] = $dataValues['number'];
$queryValue["description"] = $dataValues['description'];
$queryValue["date"] = $dataValues['date'];
$queryValue["visible_on_the_front"] = $dataValues['visible_on_the_front'];
$queryValue["id_category_page"] = $dataValues['id_category_page'];
$queryValue["visible_on_the_front2"] = $dataValues['visible_on_the_front2'];
$this->_db->query("INSERT INTO psGalleryCategories (visible_on_the_front2, id_category_page, visible_on_the_front, date, description, enable, number) VALUES (:visible_on_the_front2, :id_category_page, :visible_on_the_front, :date, :description, :enable, :number);", $queryValue);
When he writes such a string of characters:
'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2'""''
I have error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2''' at line 1 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php:78 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(78): PDOStatement->execute() #1 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(139): Core\Utilities\Db->Init('SELECT COUNT(ti...', NULL) #2 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/models/ModelClass.php(24): Core\Utilities\Db->row('SELECT COUNT(ti...') #3 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/models/GalleryModel.php(230): Core\Models\Model->createSeoUrl(''';fwefewfpew'f...', 'title_pl', 'psGalleryCatego...') #4 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/controllers/GalleryList.php(14 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php on line 78
How to fix this error?
I do not have any problems with normal string. Problem is with combination ',/, "", etc (special characters).
Please help me.
I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?
I am in the process of learning PDO and am trying to implement it in my current project. When I used mysqli, I could get detailed info about any error using mysqli_error($connection). I googled at what the comparable for PDO would be and found this post, and decided to implement it in my code. However, I am unable to get any error messages even when I know there is an obvious error in the sql statement.
Relevant code:
class Database {
public $connection;
function __construct() {
$this->open_database_connection();
}
public function open_database_connection() {
try {
$this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
echo $e->getMessage();
die('Could not connect');
}
} // end of open_database_connection method
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
foreach($params as $key => $value) {
if ($key === ':limit') {
$query->bindValue($key, $value, PDO::PARAM_INT);
} else {
$query -> bindValue($key, $value);
}
}
try {
$query->execute();
} catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
/*
DID NOT WORK:
if (!$query->execute()) {
print_r($query->errorinfo());
}*/
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->confirm_query($result);
return $result;
} // end of query method
function confirm_query($query) {
if (!$query) {
die('mysql error: ');
}
}
When I run the code, I do get the "mysql error", but I do not get any details about it. What am I doing wrong?
Update: As requested, I am providing additional details below.
What I am trying to do is get the user's login detail to be verified. To that end, once the user inputs his credentials , this code runs:
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check the database for the user
$user_found = User::verify_user($username, $password);
Relevant code from the User class:
public static function verify_user($username, $password) {
global $db;
$username = $db->escape_string($username);
$password = $db->escape_string($password);
$values = [ ":username" => $username,
":password" => $password,
":limit" => 1
];
$result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);
return !empty($result_array)? array_shift($result_array) : false;
}
public static function find_this_query($sql, $prepared = false, $params = []) {
global $db;
$the_object_array = array();
$result = $db->query($sql, $params);
$arr_length = count($result);
for ($i = 0; $i < $arr_length; $i++) {
$the_object_array[] = self::instantiation($result[$i]);
}
return $the_object_array;
}
public static function instantiation($the_record) {
$the_object =new self; //we need new self because $the_record corresponds to one user!
foreach($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public function has_the_attribute($attribute) {
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
You have to use PDO::errorInfo():
(...)
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
if( !$query )
{
$error = $this->connection->errorInfo();
die( "mysql error: {$error[2]}" );
}
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
(...)
}
PDO::errorInfo returns an array:
Element 0: SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard);
Element 1: Driver-specific error code;
Element 2: Driver-specific error message.
We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}