PHP PDO Wrapper class implementation - php

I have been developing a wrapper class inside a small PHP framework and I am experiencing something weird with one of the method in my class.
First here is the class code :
<?php
namespace Framework;
header('Content-Type: text/html; charset=UTF-8');
class cConnexion
{
public $m_log;//This will be instantiate as a cLog object (another class in the namespace)
private $m_DB;//PDO instance
private $m_Host;//Host of the conneciton string
private $m_DBName;//Name of the DB to connecte to
private $m_Driver;//Driver name, mysql for MySQL, sqlsrv for MSSQL
private $m_Login;//Username for authentification
private $m_Password;//Password for authentification
public function __construct($p_Driver = "mysql", $p_host, $p_DBName, $p_login, $p_password)
{
$this->m_Host= $p_host;
$this->m_Driver = $p_Driver;
$this->m_DBName = $p_DBName;
$this->m_Login = $p_login;
$this->m_Password = $p_password;
$this->m_log = new cLog('', '', true, false, false);
}
public function SecureExecute($p_query, $p_param)
{
try
{
$stmt = $this->m_DB->prepare($p_query);
$status = $stmt->execute($p_param);
$this->m_log->setMessageFR("Aucune exception ne s'est levé. ");
$this->m_log->setMessageEN("No exceptions were raised. ");
$this->m_log->setSuccess($status);
return $status;
}
catch(\PDOException $e)
{
$this->m_log->setMessageFR("Une exception de type PDO est levé. ".$e->getMessage());
$this->m_log->setMessageEN("A PDO exception was raised. ".$e->getMessage());
$this->m_log->setSuccess(false);
return false;
}
}
}
?>
Note that I have remove every other method that are not relevant to the question but kept the constructor and all the properties. Also note that there is a method to connect the $m_DB property to the DB, you might want to assume it has already been called.
Here is the problem I need help solving:
Step by Step description of what is going on:
I create an instance of cConnexion and use the connecteToDB method that isn't described in here but it is working properly because I can use another method to do MySQL 'SELECT' statement.
I tried to UPDATE a row which doesn't exist in a MySQL table but the object still tell me that the UPDATE was successful.
Is that normal? I read the PDO::PDOStatement::execute Doc and is says that the return value of PDO::PDOStatement::execute is either true (on success) or false(if fails).
Here is an exemple of code using the method:
$sql = "UPDATE Employes SET CieNo = 3, Nom = :Name, Dept = :Department WHERE EmplCode = :Code";
$params = array
(
'Code'=>$EmplCode,// = 123
'Name'=>($lname." ".$fname),// = Lalonde Sebastien
'Department'=>$dep,// = INFO
);
$cn = new cConnexion(/*Connection string and params here*/);
$cn->connectToDB();
if($cn->SecureExecute($sql, $params))
{
echo "SQL1: true";
}
The following code always output "SQL1: true" even when the UPDATE shouldn't had work...(because the Employes table doesn't contains an EmplCode = 123).
Can someone suggest a way to change my class so that the method SecureExecute() return false when this happen?

The execute method returns true on success, which in your case is true: The mysql query was executed successfully, however no rows were effected.
If you need to check whether the update actually altered anything, you need to use "rowCount":
$stmt = $this->m_DB->prepare('Update ...');
$stmt->execute();
$effected = $stmt->rowCount();
You can then decide if you want to return a true/false value from your method.
http://www.php.net/manual/en/pdostatement.rowcount.php

You'll only receive an error if the SQL command itself is in error. So if Employes is a valid table, and CieNo, Nom, Dept, and EmplCode are all valid columns, then your SQL statement is valid, even though it doesn't always find a row to UPDATE. Technically, it was "successful", just not in the way you're wanting.
Take a look at rowCount()
for info on how to determine whether 0 or more rows were affected by your query.

In fact, this whole class appears to be utterly useless. Exactly the same outcome can be achieved with raw PDO, with very small addition.
$cn = new PDO(/*Connection string and params here*/);
$cn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $cn->prepare($sql);
$stmt->execute($params);

Related

Php Mysqli simple class method for INSERT, UPDATE, DELETE and Search

I have the following code in my CRUD class
//function to execute prepared statement query
//$sql = select , insert, update and or delete query => insert into table(col,col,col,...col) values(?,?,?,...?);
//$dataTypes = "ssidb", it could be any char in s=>string, i=>integer, d=>double and b=>blob data
//$param = $val1,$val2,$val3,....$valn, this is an option coma separated values to bind with query
public function dbQuery($sql,$dataTypes="",$param=""){
try{
$this->connect();
$stmt = $this->con->stmt_init();
$stmt = $this->con->prepare($sql);
$stmt->bind_param($dataTypes, $param);
if($stmt->execute() === true){
return true;
}
else{
return false;
}
}catch(Exception $e){
$this->errorMsg = $e->getMessage();
}
$this->closeConnection();
}
I am calling this method from my index page like this:
if(isset($_POST['btnSearch'])){
//search for some record with primary key
$sno = intval($_POST['sno']);
$sql = "SELECT sno,std_name,email,roll_number FROM table_1 WHERE sno = ?";
$dTypes = "i";
$params = $sno;
if($db->dbQuery($sql,$dTypes,$params)){
echo('Record exists');
}
else{
echo('Record did not found'.$db->errorMsg);
}
}//search for record
//inserting values to table_1 table
This always return true either there is any record exists or not?
Whats going wrong with this code?
There are many flaws in your code, and it will never work as intended, even after fixing this particular problem.
Before starting with a class, you need to practice heavily with raw API functions, and learn how to use them by heart. Otherwise your class will be just a straw house that will crumble from a softest touch.
Now to your problem.
To solve it, you need to understand one very important mathematical conception, that reads "empty result is not an error". 10 - 5 - 5 = 0 doesn't mean there is an error in your calculations! It merely means that the result is zero.
Exacly the same is here. When a database returns no rows, it doesn't mean there is an error. It just meams that there is zero (no) data to return.
The opposite is true as well: if there is no error, it doesn't mean that there are rows found.
To see whether any row were returned or not, you need to fetch this very row.
Therefore, instead of checking execute() result, just fetch your row into a variable and then check whether it contains anything.

ADODB and SQL SERVER functions

I have a web service, that connects to my MSSQL data base using ADODB for PHP. Then, I created a simple function to return a string, just for tests, but, I'll implement with another logic.
Here is my SQL SERVER FUNCTION:
USE [myDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [myDB].[VerifyUser]
(
#user varchar(50),
#pass varchar(50)
)
RETURNS varchar(32)
AS
BEGIN
DECLARE #token varchar(32);
SET #token = 'Works!';
RETURN #token;
END
And, this is my web service method:
function wseAutenticacao($usuario, $senha) {
require_once('include/adodb5/adodb.inc.php');
$db = &ADONewConnection('mssqlnative');
$db->Connect(<host>, <user>, <pass>, <db_name>);
$stmt = $db->Prepare('VerifyUser');
$db->InParameter($stmt, $usuario, 'user');
$db->InParameter($stmt, $senha, 'pass');
$db->OutParameter($stmt, $token, 'token');
$result = $db->Execute($stmt);
return array('result' => $result);
}
I don't get the string "Works!" returned by my sql function. What is returned is a boolean with a false value, like I'm doing something wrong, but, I followed the ADODB Documentation example and now, I don't know what I have to do. I'm stuck!
If anyone would share your knowledge, I'll be greatful!
Thanks!
The #token local variable is only visible within the function itself. The result of the scalar function needs to be assigned to the output parameter in the executed script. One method you could try is a parameterized SELECT statement to assign the function return value to the output parameter:
$stmt = $db->Prepare('SELECT #token = VerifyUser(#user, #pass);');
I know the thread is old, but I'm looking for a solution for something similar. It seems that the current implementation of 'mssqlnative' does not support parameters at all. That is, the base class ADOConnection implements a mock metod Parameter which should be overridden in subclasses. ADODB_mssqlnative does not have an override of this method, hence, your parameters disappear into the void. Next thing, the current implementaton of _query() expects input parameters as array.
So, you could change your code to this to make it work
$db = &ADONewConnection('mssqlnative');
$db->Connect(<host>, <user>, <pass>, <db_name>);
$stmt = 'VerifyUser';
$params = array($usuario, $senha, $token);
$result = $db->Execute($stmt, $params);
return array('result' => $result);
Also, note that the params array is not associative. The current implementation of sqlsrv_query does not allow named parameters.

ZF2 already active query prevents execution

I have something like the following, in a function that deletes both the files and db entries:
$adapter = $this->getAdapter();
$query = $adapter->query("call find_results_by_job_id(?)", array($jobId));
$items = array();
while (($current = $query->current()) !== false)
{
$id = $current['id'];
$items[] = $id;
$query->next();
}
$this->deleteFromDataStore($items);
$result = $adapter->query("call delete_results_by_job_id(?)", array($jobId), \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
(Some of that might not look like the best way to do it, because I simplified it for this example)
I'm getting this error on the last line: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.
I'm assuming that the problem is because the query/adapter hasn't closed the connection from iterating results yet when I try to execute another statement. If that is the case, how can reuse the adapter, or close the query, or whatever I have to do before the last line?
The strange part is that code following almost exactly this same pattern works in another method.
Answer:
When using the PDO driver, $query->getDataSource()->getResource()->closeCursor(); fixes it
Seems like you are using an unbuffered query in MySQL.
If it is so, you will either have to turn buffering on or break execution of previous query which seems to hang?
Something like $query->close()
EDIT:
If $query is instance of StatementInterface, then there is getResource() which returns mysqli_stmt and you can call close() on it.
EDIT2: (to incorporate final resolution)
In case it uses PDO, you can get PDOStatement and call closeCursor()
Assuming you have the result of a query in your hands and you dont know whether it is a ResultSet or a Result, the following will do the job.
Tested as of Zend Framework 3.
use Zend\Db\ResultSet\ResultSet;
...
public function closeResult( $result )
{
if( is_a($result, ResultSet::class) )
{
$stmt = $result->getDataSource()->getResource();
}
else
{
$stmt = $result->getResource();
}
$stmt->closeCursor();
}
$this->adapter
->query($sql)
->execute()
->getResource()
->fetchAll(\PDO::FETCH_ASSOC);

Creating a container function for a PDO query in PHP

Because I find PDO executions extremely hard to remember and find myself looking back at previous projects or other websites just to remember how to select rows from a database, I decided that I would try and create my own functions that contain the PDO executions and just plug in the data I need. It seemed a lot simpler than it actually is though...
So far I have already created a connect function successfully, but now when it comes to create a select function I'm stumped for multiple reasons.
For starters there could be a variating amount of args that can be passed into the function and secondly I can't figure out what I should pass to the function and in which order.
So far the function looks like this. To keep me sane, I've added the "id" part to it so I can see what exactly I need to accomplish in the final outcome, and will be replaced by variables accordingly when I work out how to do it.
function sql_select($conn, **what to put here**) {
try {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
return "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
So far what I've established that the function will need to do is
Connect to the database (using another function to generate the $conn variable, already done)
Select the table
Specify the column
Supply the input to match
Allow for possible args such as ORDER by 'id' DESC
Lastly from this I would need to create a function to insert, update and delete rows from the database.
Or, is there a better way to do this rather than functions?
If anyone could help me accomplish my ambitions to simply simplify PDO executions it would be greatly appreciated. Thanks in advance!
First of all, I have no idea where did you get 10 lines
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = ?');
$stmt->execute(array($id));
$result = $stmt->fetchAll();
is ALL the code you need, and it's actually three lines, which results with a regular PHP array that you can use wherever you wish. Without the need of any PDO code. Without the need of old mysql code.
Lastly from this I would need to create a function to insert, update and delete rows from the database.
DON'T ever do it.
Please read my explanations here and here based on perfect examples of what you'll end up if continue this way.
accomplish my ambitions to simply simplify PDO executions
That's indeed a great ambition. However, only few succeeded in a real real simplification, but most resulted with actually more complex code. For starter you can try code from the first linked answer. Having a class consists of several such functions will indeed improve your experience with PDO.
. . . and find myself looking back at previous projects or other
websites just to remember how to select rows from a database . . .
FYI, we all do that.
You had a problem with the PDO API and now you have two problems. My best and strongest suggestion is this: If you want a simpler/different database API, do not roll your own. Search http://packagist.org for an ORM or a DBAL that looks good and use it instead of PDO.
Other people have already done this work for you. Use their work and focus instead on whatever awesome thing is unique to your app. Work smart, not hard and all that.
Writting a wrapper, should start form connecting the DB, and all the possible method could be wrapped. Passing connection to the query method, doesn't look good.
A very rough example would be the code bellow, I strongly do not suggest this mixture, but it will give you the direction.
You connection should be made either from the constructor, or from another method called in the constructor, You can use something like this:
public function __construct($driver = NULL, $dbname = NULL, $host = NULL, $user = NULL, $pass = NULL, $port = NULL) {
$driver = $driver ?: $this->_driver;
$dbname = $dbname ?: $this->_dbname;
$host = $host ?: $this->_host;
$user = $user ?: $this->_user;
$pass = $pass ?: $this->_password;
$port = $port ?: $this->_port;
try {
$this->_dbh = new PDO("$driver:host=$host;port=$port;dbname=$dbname", $user, $pass);
$this->_dbh->exec("set names utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
So you can either pass connection credentials when you instantiate your wrapper or use default ones.
Now, you can make a method that just recieves the query. It's more OK to write the whole query, than just pass tables and columns. It will not make a whole ORM, but will just make the code harder to read.
In my first times dealing with PDO, I wanted everything to be dynamically, so what I achieved, later I realized is immature style of coding, but let's show it
public function query($sql, $unset = null) {
$sth = $this->_dbh->prepare($sql);
if($unset != null) {
if(is_array($unset)) {
foreach ($unset as $val) {
unset($_REQUEST[$val]);
}
}
unset($_REQUEST[$unset]);
}
foreach ($_REQUEST as $key => $value) {
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
$param = FALSE;
}
$sth->bindValue(":$key", $value, $param);
}
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
So what all of these spaghetti does?
First I though I would want all of my post values to be send as params, so if I have
input name='user'
input name='password'
I can do $res = $db->query("SELECT id FROM users WHERE username = :user AND password = :password");
And tada! I have fetched result of this query, $res is now an array containing the result.
Later I found, that if I have
input name='user'
input name='password'
input name='age'
In the same form, but the query remains with :user and :password and I submit the form, the called query will give mismatch in bound params, because the foreach against the $_REQUEST array will bind 3 params, but in the query I use 2.
So, I set the code in the beginning of the method, where I can provide what to exclude. Calling the method like $res = $db->query("SELECT id FROM users WHERE username = :user AND password = :password", 'age'); gave me the possibility to do it.
It works, but still is no good.
Better have a query() method that recieves 2 things:
The SQL string with the param names
The params as array.
So you can use the foreach() logic with bindValue, but not on the superglobal array, but on the passed on.
Then, you can wrap the fetch methods
public function fetch($res, $mode = null)
You should not directly return the fetch from the query, as it might be UPDATE, INSERT or DELETE.
Just pass the $res variable to the fetch() method, and a mode like PDO::FETCH_ASSOC. You can use default value where it would be fetch assoc, and if you pass something else, to use it.
Don't try to be so abstract, as I started to be. It will make you fill cracks lately.
Hum... IMHO I don't think you should try to wrap PDO in functions, because they're already "wrapped" in methods. In fact, going from OOP to procedural seems a step back (or at least a step in the wrong direction). PDO is a good library and has a lot of methods and features that you will surely lose if you wrap them in simple reusable functions.
One of those features is the BeginTransaction/Rollback (see more here)
Regardless, In a OOP point of view you can decorate the PDO object itself, adding some simple methods.
Here's an example based on your function
Note: THIS CODE IS UNTESTED!!!!
class MyPdo
{
public function __construct($conn)
{
$this->conn = $conn;
}
public function pdo()
{
return $this->conn;
}
public function selectAllById($table, $id = null)
{
$query = 'SELECT * FROM :table';
$params = array('table'=>$table);
if (!is_null($id)) {
$query .= ' WHERE id = :id';
$params['id'] = $id;
}
$r = $this->conn->prepare($query)
->execute($params)
->fetchAll();
//More stuff here to manipulate $r (results)
return $r;
}
public function __call($name, $params)
{
call_user_func_array(array($this->conn, $name), $params);
}
}
Note: THIS CODE IS UNTESTED!!!!
ORM
Another option is using an ORM, which would let you interact with your models/entities directly without bothering with creating/destroying connections, inserting/deleting, etc... Doctrine2 or Propel are good bets for PHP.
Howeveran ORM is a lot more complex than using PDO directly.

Unable to insert new data into MySQL database after deleting an entry using PHPMyAdmin

I managed to run the following code to insert into my table on first try. Then, I deleted that row in PHPMyAdmin to test my code further. I also noticed that it didn't get deleted on the 1st try. Only after few try. This might be due to I didn't set the $pdoHandle to NULL after I'm done with the query.
Then, unfortunately I couldn't insert new row on subsequent run. I even tried to change the input value and to avail I was unable to insert new row. The following are my PHP codes:
public function CreateNewCustomer($userId,$password,$name,$email)
{
$userId = filter_var($userId,FILTER_SANITIZE_STRING);
$password = filter_var($password,FILTER_SANITIZE_STRING);
$password = sha1($password);
$name = filter_var($name,FILTER_SANITIZE_STRING);
$email = filter_var($email,FILTER_SANITIZE_EMAIL);
do{
$customerId = hexdec(bin2hex(openssl_random_pseudo_bytes(4,$isStrong)));
echo $customerId;
$result = $this->connObject->exec("SELECT COUNT(id) FROM customer_tbl WHERE id=$customerId");
var_dump($result);
}while($result>0);
$statement = $this->connObject->prepare("INSERT INTO customer_tbl (id,name,email) VALUES ($customerId,:name,:email)");
$result = $statement->execute(array(':name'=>$name,':email'=>$email ));
var_dump($result);
$statement = $this->connObject->prepare("INSERT INTO login_tbl (username,password,customer_id) VALUES (:userName,PASSWORD(:password),$customerId)");
$result = $statement->execute(array(':userName'=>$userId,':password'=>$password ));
var_dump($result);
}
I used the following code to access the above method.
function Test($userName,$password,$name,$email)
{
try
{
$dbConnect = new DbConnect();
$pdoHandle = $dbConnect->Connect();
$userAccess = new UserAccess($pdoHandle);
$userAccess->CreateNewCustomer($userName,$password,$name,$email);
}
catch(PDOException $e)
{
$pdoHandle = null;
var_dump($e);
}
$pdoHandle = null;
}
Test('tester','password','TestX','test#example.com');
The var_dump of results is always false.
Is there any problem with my codes or is it something wrong with the database?
UPDATE/SOLUTION:
I just read through the PHP document on PDO::exec() and one of the user contributed notes mentioned that you can't use any SELECT statements (even thou the above only returns the count value) and any statements which might return a rows. The return value of PDO::exec() is the number of affected rows (integer), so the PDOStatement::closeCursor() can't be used to solve it. Even when I set the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true, it still doesn't work.
So, don't use PDO::exec() for any SELECT. I changed my code to PDO::query() instead as below,
do{
$customerId = hexdec(bin2hex(openssl_random_pseudo_bytes(4,$isStrong)));
$statement = $this->connObject->query("SELECT COUNT(id) FROM customer_tbl WHERE id=$customerId");
$statement->execute();
}while($statement->fetchColumn(0)>0);
Hope this would be helpful to anyone looking for a solution with similar problem and always remember to read the PHP document first including the user contributions.
Maybe not the answer but here are some things that you can do if you cannto see an obvious error:
If execute returns false, you can get more information about the error that happened by:
$arr = $statement->errorInfo();
print_r($arr);
or you can set different error reporting modes (e.g. throw an exception instead of the defaultsilent mode):
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This should help you to find the "real" error.
As it turned out (see comments below question), in this case the real error was:
"Cannot execute queries while other unbuffered queries are active.
Consider using PDOStatement::fetchAll(). Alternatively, if your code
is only ever going to run against mysql, you may enable query
buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY"
In this case you have 2 options:
you can set the option to use buffered queries
$dbh = new PDO(’mysql:host=localhost;dbname=test’, ‘root’, ” ,array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true))
or change your code and close an open cursor (may depend on the db driver you are using). You always should read the documentation which covers a lot of default problems.
Hope this helps.
I'm assuming the method is inside the UserAccess class and the connection you pass in is set to the local $this->connObject.
I suspect after you deleted the record, $customerId is being set to null in your interesting do-while loop with the select statement. If the id column in the DB is a non-null primary key field and you try to insert an explicit null it will fail.
Also, no need to keep setting your DB connection to null... this isn't C and connections aren't persistent (unless you explicitly declare them as such).

Categories