Inserting multiple rows at once with prepared statements - php

I would like to know how can I insert multiple values in an array via prepared statements. I've looked at these two (this question and this other one ) questions but they don't seem to do what I'm trying. This is what I have:
$stmt = $this->dbh->prepare("INSERT INTO
t_virtuemart_categories_en_gb
(category_name, virtuemart_category_id)
VALUES
(:categoryName, :categoryId)
;");
foreach($this->values as $insertData){
$categoryName = $insertData['categoryName'];
$categoryId = $insertData['categoryId'];
$stmt->bindParam(':categoryName', $categoryName);
$stmt->bindParam(':categoryId', $categoryId);
$stmt->execute();
}
I tried placing the prepare line inside the foreach loop and outside, but it only adds the first key in the array, and I don't understand why.
This is my Connection.php file:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
function connectDB ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
return $dbh;
}
try {
$dbh = connectDB ($hostname, $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
And my Import.php file:
<?php
class Import{
public function __construct($dbh, $values) {
$this->dbh = $dbh;
$this->values = $values;
}
public function importData() {
$stmt = $this->dbh->prepare("INSERT INTO
t_virtuemart_categories_en_gb
(category_name, virtuemart_category_id)
VALUES
(:categoryName, :categoryId)
;");
foreach($this->values as $insertData){
$categoryName = $insertData['categoryName'];
$categoryId = $insertData['categoryId'];
$stmt->bindParam(':categoryName', $categoryName);
$stmt->bindParam(':categoryId', $categoryId);
$stmt->execute();
}
}
}

Working principle:
Use only one INSERT sql statement to add multiple records, defined by your values pairs. In order to achieve this you have to build the corresponding sql statement in the form
INSERT INTO [table-name] ([col1],[col2],[col3],...) VALUES (:[col1],:[col2],:[col3],...), (:[col1],:[col2],:[col3],...), ...
by iterating through your values array.
Notes:
I hope you'll understand all. I commented as much as I could. I
didn't test it, but it should work. Maybe an answer I wrote a
short time ago will give you further ideas regarding structuring of
data access classes/functions as well.
Never use ";" at the end of the sql statements when you define them in PHP.
Never use one input marker to bind multiple values. For each value to bind use a unique named input marker.
Good luck.
Connection.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$port = 3306;
try {
// Create a PDO instance as db connection to a MySQL db.
$connection = new PDO(
'mysql:host='. $hostname .';port='.$port.';dbname=test'
, $username
, $password
);
// Assign the driver options to the db connection.
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$connection->setAttribute(PDO::ATTR_PERSISTENT, TRUE);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
} catch (Exception $exc) {
echo $exc->getMessage();
exit();
}
Import.php:
<?php
class Import {
/**
* PDO instance as db connection.
*
* #var PDO
*/
private $connection;
/**
*
* #param PDO $connection PDO instance as db connection.
* #param array $values [optional] Values list.
*/
public function __construct(PDO $connection, array $values = array()) {
$this->connection = $connection;
$this->values = $values;
}
/**
* Import data.
*
* #return int Last insert id.
* #throws PDOException
* #throws UnexpectedValueException
* #throws Exception
*/
public function importData() {
/*
* Values clauses list. Each item will be
* later added to the sql statement.
*
* array(
* 0 => '(:categoryName0, :categoryId0)',
* 1 => '(:categoryName1, :categoryId1)',
* 2 => '(:categoryName2, :categoryId2)',
* )
*/
$valuesClauses = array();
/*
* The list of the input parameters to be
* bound to the prepared statement.
*
* array(
* :categoryName0 => value-of-it,
* :categoryId0 => value-of-it,
* :categoryName1 => value-of-it,
* :categoryId1 => value-of-it,
* :categoryName2 => value-of-it,
* :categoryId2 => value-of-it,
* )
*/
$bindings = array();
/*
* 1) Build a values clause part for each array item,
* like '(:categoryName0, :categoryId0)', and
* append it to the values clauses list.
*
* 2) Append each value of each item to the input
* parameter list.
*/
foreach ($this->values as $key => $item) {
$categoryName = $item['categoryName'];
$categoryId = $item['categoryId'];
// Append to values clauses list.
$valuesClauses[] = sprintf(
'(:categoryName%s, :categoryId%s)'
, $key
, $key
);
// Append to input parameters list.
$bindings[':categoryName' . $key] = $categoryName;
$bindings[':categoryId' . $key] = $categoryId;
}
/*
* Build the sql statement in the form:
* INSERT INTO [table-name] ([col1],[col2],[col3]) VALUES
* (:[col1],:[col2],:[col3]), (:[col1],:[col2],:[col3]), ...
*/
$sql = sprintf('INSERT INTO t_virtuemart_categories_en_gb (
category_name,
virtuemart_category_id
) VALUES %s'
, implode(',', $valuesClauses)
);
try {
// Prepare the sql statement.
$statement = $this->connection->prepare($sql);
// Validate the preparing of the sql statement.
if (!$statement) {
throw new UnexpectedValueException('The sql statement could not be prepared!');
}
/*
* Bind the input parameters to the prepared statement
* and validate the binding of the input parameters.
*
* -----------------------------------------------------------------------------------
* Unlike PDOStatement::bindValue(), when using PDOStatement::bindParam() the variable
* is bound as a reference and will only be evaluated at the time that
* PDOStatement::execute() is called.
* -----------------------------------------------------------------------------------
*/
foreach ($bindings as $key => $value) {
// Read the name of the input parameter.
$inputParameterName = is_int($key) ? ($key + 1) : (':' . ltrim($key, ':'));
// Read the data type of the input parameter.
if (is_int($value)) {
$inputParameterDataType = PDO::PARAM_INT;
} elseif (is_bool($value)) {
$inputParameterDataType = PDO::PARAM_BOOL;
} else {
$inputParameterDataType = PDO::PARAM_STR;
}
// Bind the input parameter to the prepared statement.
$bound = $statement->bindValue($inputParameterName, $value, $inputParameterDataType);
// Validate the binding.
if (!$bound) {
throw new UnexpectedValueException('An input parameter could not be bound!');
}
}
// Execute the prepared statement.
$executed = $statement->execute();
// Validate the prepared statement execution.
if (!$executed) {
throw new UnexpectedValueException('The prepared statement could not be executed!');
}
/*
* Get the id of the last inserted row.
*/
$lastInsertId = $this->connection->lastInsertId();
} catch (PDOException $exc) {
echo $exc->getMessage();
// Only in development phase !!!
// echo '<pre>' . print_r($exc, TRUE) . '</pre>';
exit();
} catch (Exception $exc) {
echo $exc->getMessage();
// Only in development phase !!!
// echo '<pre>' . print_r($exc, TRUE) . '</pre>';
exit();
}
return $lastInsertId;
}
}

I think the statements have to be prepared and bound separately for each iteration:
if($stmt = $this->dbh->prepare("INSERT INTO t_virtuemart_categories_en_gb (category_name, virtuemart_category_id) VALUES (:categoryName, :categoryId);")){
foreach($this->values as &$insertData){
$stmt->bindParam(':categoryName', $insertData['categoryName']);
$stmt->bindParam(':categoryId', $insertData['categoryId']);
$stmt->execute();
$stmt->close();
}
}

I would suggest this, using a $dbh = mysqli_connect():
<?php
class Import{
public function __construct($dbh, $values) {
$this->dbh = $dbh;
$this->values = $values;
}
public function importData() {
$stmt = $this->dbh->prepare("INSERT INTO t_virtuemart_categories_en_gb
(category_name, virtuemart_category_id)
VALUES
(?, ?)");
$catetoryName = ''; $categoryId = '';
$stmt->bind_param('ss', $categoryName, $categoryId);
foreach($this->values as $insertData){
$categoryName = $insertData['categoryName'];
$categoryId = $insertData['categoryId'];
$stmt->execute();
}
}
}
In this way you create a reference and bind that variable to the execution of the prepared statement.
You should be careful about it when passing an array, the trick is commented in the php.net page ( http://php.net/manual/it/mysqli.prepare.php )
A code that work is:
$typestring = 'sss'; //as many as required: calc those
$stmt = $dbconni->prepare($ansqlstring);
$refs = [$typestring];
// if $source is an array of array [ [f1,f2,...], [f1,f2,...], ...]
foreach($source as $data) {
if (count($refs)==1) {
foreach ($data as $k => $v) {
$refs[] = &$data[$k];
}
$ref = new \ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($stmt, $refs);
$r = $stmt->execute();
} else {
// references are maintained: no needs to bind_param again
foreach ($data as $k => $v) {
$refs[$k+1] = $v;
}
$r = $stmt->execute();
}
}
this spare resources and is more performant, but you have to make benchmark to be sure about my words.
this is one of the case where prepared statement make sense, see
https://joshduff.com/2011-05-10-why-you-should-not-be-using-mysqli-prepare.md
Normally PDO emulate prepared statement, see PDO::ATTR_EMULATE_PREPARES
EDIT: specify it is using mysqli, and correct the code.

Related

PDO query class

I'm tinkering with a class that 'should' allow me to easily execute a fetchall query and display the results within a foreach statement. I assume all is working correctly as I have no errors. As for the foreach - this must be the problem? How would I foreach the results gained from the $connect->query()? I'm new to using any database OOP framework in my functions so I could be along the wrong lines completely.
<?
error_reporting(1);
class dbconnect {
private $host;
private $database;
private $username;
private $password;
private $pdo;
private $error;
public function __construct() {
$this->host = "localhost"; // Host
$this->database = "images"; // Database Name
$this->username = "*"; // Username
$this->password = "*"; // Password
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
try {
$this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options);
}
catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query) {
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute();
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
return $rows;
}
}
$connect = new dbconnect;
$rows = $connect->query("select * from photos");
foreach($rows as $row):
print $row['id'];
endforeach;
?>
The $rows variable you're declaring inside query is not accessible to the outside, it is local to that function. Most likely, you simply want to return those results to the caller:
$rows = $stmt->fetchAll();
return $rows; // return value from function...
and have the caller capture that return value in its own variable:
$rows = $connect->query("select * from images"); // ... is received by caller
foreach($rows as $row):
Also check out dougjore's answer, you're mixing $this->stmt and $stmt inside your query method.
Pretty sure you aren't ever actually executing the query:
$this->stmt = $this->pdo->prepare($query);
$stmt->execute();
I believe (I could be wrong, I'm rather new to PDO myself and I haven't built a class for it), that you need to say $this->stmt->execute();
You could do
//PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
$this->stmt = $this->pdo->prepare($query);
$this->stmt->execute();
while ($result = $this->stmt->fetch(PDO::FETCH_ASSOC))
{
//do something with the result
}
Have a look here for more options to fetch PDO query results:
http://php.net/manual/en/pdostatement.fetch.php
$connect = new dbconnect;
$sql="select * from photos";
$stmt=$connect->pdo->prepare($sql);
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}

How to use prepared statements (named parameters) on a php Class

I want to know how to use named parameters in a prepared statement with pdo class, so the call to pdo look something like following.
$query = $bdd->prepare('SELECT * FROM table WHERE login = :login AND pww = :pww');
$query->execute(array('login' => $login, 'pww' => $pww));
And I want to integrate this on a class regardless of the number of parameters.
Currently, I have this code
require_once 'constants.php';
class Mysql extends PDO {
private $con;
public function __construct() {
try {
$this->con = parent::__construct(DB_DSN, DB_USER, DB_PASS);
if ($this->getAttribute(PDO::ATTR_DRIVER_NAME) == DB_TYPE)
$this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
return $this->con;
} catch (PDOException $e) {
die('Error:' . $e->getMessage());
}
}
public function select($reqSelect) {
try {
$this->con = parent::beginTransaction();
$result = parent::prepare($reqSelect);
$result->execute();
//$this->con = parent::commit();
$this->con = parent::rollBack();
return $result;
$result->closeCursor();
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
}
public function selectAll($reqSelect) {
$result = parent::prepare($reqSelect);
$result->execute();
$resultat = $result->fetchAll();
return $resultat;
$result->closeCursor();
}
}
And for parameters, I use somethings like ( which is wrong and vulnerable to injection )
require_once 'classes/Mysql.class.php';
$mysql = new Mysql();
$sql = 'SELECT * FROM articles WHERE id = '.$_GET['id'].' LIMIT 1';
$data = $mysql->select($sql);
Thanks.
So it's seems that I have figured it out, the trick was adding an optional parameter to the function, you use it whenever you need to work with prepared statements (named parameters).
So the function is something like
public function selectAll($reqSelect, $param = null) {
$result = parent::prepare($reqSelect);
//Check whether the parameter was passed or not
if (is_null($param)) {
$result->execute();
$resultat = $result->fetchAll();
return $resultat;
} else {
//Binding the parameters
$result->execute($param);
$resultat = $result->fetchAll();
return $resultat;
}
$result->closeCursor();
}
And for applying it, it goes like
//First param, the SQL. Here we have named parameters, so we need them to get bind
$sql = 'SELECT * FROM articles WHERE publish = :number';
//Second param, the parameters that will get bind with the named ones
$param = array(':number' => 1);
$query = $mysql->selectAll($sql, $param);
foreach ($query as $row) {
extract($row);
echo $title . '<br />';
}
I don't know if this, is considered the best practice, secured or even correct. if I'm mistaken feel free to correct me.

Get Last Executed Query in PHP PDO

I would like to know what query is executed using PHP PDO. I have:
<?php
try {
$DBH = new PDO("mysql:host=localhost;dbname=mytable", 'myuser', 'mypass');
}
catch(PDOException $e) {
echo $e->getMessage();
}
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->("INSERT INTO mytable (column1, column2, column3 /* etc...*/) value (:column1, :column2, :column3 /* etc...*/)");
$STH->bindParam(':column1', $column1);
$STH->bindParam(':column2', $column2);
$STH->bindParam(':column3', $column3);
/* etc...*/
$STH->execute();
// what is my query?
I would like to get something like:
INSERT INTO mytable (column1, column2, column3) value ('my first column', 32, 'some text')
Is it possible? Thanks
<?php
class MyPDOStatement extends PDOStatement
{
protected $_debugValues = null;
protected function __construct()
{
// need this empty construct()!
}
public function execute($values=array())
{
$this->_debugValues = $values;
try {
$t = parent::execute($values);
// maybe do some logging here?
} catch (PDOException $e) {
// maybe do some logging here?
throw $e;
}
return $t;
}
public function _debugQuery($replaced=true)
{
$q = $this->queryString;
if (!$replaced) {
return $q;
}
return preg_replace_callback('/:([0-9a-z_]+)/i', array($this, '_debugReplace'), $q);
}
protected function _debugReplace($m)
{
$v = $this->_debugValues[$m[1]];
if ($v === null) {
return "NULL";
}
if (!is_numeric($v)) {
$v = str_replace("'", "''", $v);
}
return "'". $v ."'";
}
}
// have a look at http://www.php.net/manual/en/pdo.constants.php
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STATEMENT_CLASS => array('MyPDOStatement', array()),
);
// create PDO with custom PDOStatement class
$pdo = new PDO($dsn, $username, $password, $options);
// prepare a query
$query = $pdo->prepare("INSERT INTO mytable (column1, column2, column3)
VALUES (:col1, :col2, :col3)");
// execute the prepared statement
$query->execute(array(
'col1' => "hello world",
'col2' => 47.11,
'col3' => null,
));
// output the query and the query with values inserted
var_dump( $query->queryString, $query->_debugQuery() );
Most people create a wrapper class around the PDO object to record the queries as they are sent to the database. Hardly anyone uses a direct PDO object since you can add extra helper methods by wrapping, or extending PDO.
/**
* Run a SQL query and return the statement object
*
* #param string $sql query to run
* #param array $params the prepared query params
* #return PDOStatement
*/
public function query($sql, array $params = NULL)
{
$statement = $this->pdo->prepare($sql);
$statement->execute($params);
// Save query results by database type
self::$queries[] = $sql;
return $statement;
}

What is the simplest way to return a ROW as well as loop through the ROWS with PDO?

If I am doing an old query to return a row I would do something like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
echo $row['id'];
How do I do that with a Prepared Statement? I can get this far...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to pull out this one row?
}
Secondly, if I have multiple rows I would do it like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
echo $row['id'];
}
Likewise, with PDO I get to a similar place...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to loop through the rows??
//
// something like this...?
//
while ($row = $stmt->fetch()) {
echo $row['id'];
}
}
Assuming you're connected to the DB and $dbh is your PDO object.
<?php
$email = 'myEmail#somesite.com';
$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);
$stmt->execute();
/* One row. */
$result = $stmt->fetch();
if ($result !== FALSE) {
$stmt->closeCursor();
echo $result['id'];
}
/* Multiple rows. */
$result = $stmt->fetchAll();
if ($result !== FALSE) {
foreach ($result as $row) {
echo $row['id'];
}
}
?>
Here is what I use:
For more info on PDO see: http://php.net/manual/en/book.pdo.php
How to use:
//create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;
//query
$sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
$values = array(":Abbr" => "AL");
$query = new Query($conn);
$testArr = $query->getArrayFromQuery($sql, $values);
CONNECTION: (Connection.php)
class Connection
{
public $conn = null;
/**
* Creates PDO Database Connection
*
* #param array $params Connection Data (host,database,username,password)
* #param bool $useErrorReporting True to Show Errors (optional)
* #sets Database Connection
* #access public
*/
public function __construct($params,$useErrorReporting=false)
{
try
{
$host = "";
$database = "";
$username = "";
$password = "";
if(isset($params) && is_array($params))
{
$host = $params['database_connection']['host'];
$database = $params['database_connection']['database'];
$username = $params['database_connection']['username'];
$password = $params['database_connection']['password'];
$dsn = 'mysql:dbname='.$database.';host='.$host;
$dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));
//display errors if true
if($useErrorReporting)
{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
else
{
$dbh = null;
}
}
catch (PDOException $e)
{
throw new Exception('Connection Failed: '.$e->getMessage());
}
$this->conn = $dbh;
}
QUERY: Query.php
Class Query
{
private $conn = null;
/**
* sets query properties
*
* #param object $conn pdo connection object
* #return void
* #access public
*/
public function __construct($conn)
{
$this->conn = $conn;
}
/**
* getArrayFromQuery
* gets array from given query
*
* #param string $sql sql statement
* #param array $values array values to replace (":value" => 2)
* #return array
* #access public
*/
public function getArrayFromQuery($sql, $values)
{
$retValue = array();
$conn = $this->conn;
$statement = "";
try
{
//prepare sql statement
$statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
//add values
if(isset($values) && is_array($values))
{
$statement->execute($values);
}
//set return array to result array
$retValue = $statement->fetchAll();
}
catch (PDOException $e)
{
throw new Exception("PDO Query Error: ".$e->getMessage());
}
catch(Exception $e)
{
throw new Exception("Process Query Error: ". $e->getMessage());
}
return $retValue;
}
}

Insert/update helper function using PDO

I have a very simple helper function to produce SET statement for traditional plain mysql driver usage:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
used like this
$id = intval($_POST['id']);
$fields = explode(" ","name surname lastname address zip fax phone");
$_POST['date'] = $_POST['y']."-".$_POST['m']."-".$_POST['d'];
$query = "UPDATE $table SET ".dbSet($fields)." stamp=NOW() WHERE id=$id";
it makes code quite DRY and easy but flexible at the same time.
I gotta ask if anyone willing to share a similar function, utilizing PDO prepared statements feature?
I am still in doubts, how to accomplish this.
Is there a straight and simple way to use PDO prepared statements to insert data?
What form it should be? Query builder helper? Or insert query helper? What parameters it should take?
I hope it can be easy enough to be used as an answer here on SO. Because in the every topic we can see prepared statements usage recommendation, but there is not a single good example. Real life example, I mean. To type bind_param() 20 times is not a good programming style I believe.
And even 20 question marks too.
I usually have a class extending PDO, but my class is pretty custom. If I get it cleaned up and tested I will post it at a later time. Here is a solution to your system, however.
function dbSet($fields, &$values) {
$set = '';
$values = array();
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set .= "`$field` = ?,";
$values[] = $_POST[$field];
}
}
return rtrim($set, ',');
}
$fields = explode(" ","name surname lastname address zip fax phone date");
$_POST['date'] = $_POST['y']."-".$_POST['m']."-"$_POST['d'];
$query = "UPDATE $table SET ".dbSet($fields, $values).", stamp=NOW() WHERE id=?";
$values[] = $id;
$dbh->prepare($query);
$dbh->execute($values);
This may not be perfect and could use tweaking. It takes into account that $dbh is setup with a PDO Connection. Pending any minor syntax issues I made, that should work.
EDIT
Really though, I think I would go for Doctrine ORM (or another ORM). As you setup the model and add all the validation there, then it is as simple as:
$table = new Table();
$table->fromArray($_POST);
$table->save();
That should populate the contents easily. This is of course with an ORM, like Doctrine.
UPDATED
Did some minor tweaks to the first code, such as putting isset back and using rtrim over substr. Going to work on providing a mock up of a PDO Extension class just gotta layout the way to do it and do some unit tests to make sure it works.
Thanks to everyone.
Every answer was helpful and I wish I could split the bounty.
At the end, to my surprise, I was able to make it the same way as before, based on on accepted answer
$fields = array("login","password");
$_POST['password'] = MD5($_POST['login'].$_POST['password']);
$stmt = $dbh->prepare("UPDATE users SET ".pdoSet($fields,$values)." WHERE id = :id");
$values["id"] = $_POST['id'];
$stmt->execute($values);
It can be wrapped into a helper function, but I doubt there is necessity. It will shorten the code by just one line.
pdoSet code:
function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`$field`=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}
i would extend the Core PDO Class andd a method like so:
class Database extends PDO
{
public function QueryFromPost($Query,$items)
{
$params = array();
$Query .= ' WHERE ';
foreach($items as $key => $default)
{
$Query .= ' :' . $key. ' = ' . $key;
if(isset($_POST[$key]))
{
$params[':' . $key] = $_POST[$key];
}else
{
$params[':' . $key] = $default;
}
}
$s = $this->prepare($Query);
return $s->execute($params);
}
}
Then use like so
$db = new Database(/*..Default PDO Params*/);
$statement = $db->QueryFromPost('SELECT * FROM employees',array('type' => 'plc'));
foreach($preparedStatement->fetchAll() as $row)
{
//...
}
But as its already been said that you should be VERY weary of what your trying to do, you need to validate your data, its been sanitized but you not validated.
I've been patching something trivial together for what I consider recurring parameter binding cases.
http://fossil.include-once.org/hybrid7/wiki/db
Anyway; it provides some alternative prepared statement placeholders. Your example could be shortened into:
db("UPDATE table SET :, WHERE id=:id", $columns[], $where[]);
This case only works with named parameters, so $set would be array("name"=>..) and $where=array("id"=>123). The :, gets expanded on the first array you pass. It's replaced with comma-separated name=:name pairs (that's why its mnemonic is :,).
There are a few more placeholders :, :& :: and :? for different use cases. Only the ?? is really somewhat of a standard. So it needs some getting used to, but it significantly simplifies prepared statements and array binding (which PDO doesn't do natively).
Here's my general database abstraction class. Take a look at the autoExecute() function. It offers tons of flexibility for whatever it is you might want to accomplish. I should warn that this was written for PHP 5.3, and has been slightly tailored for PostgreSQL.
<?php
/**
* Database abstraction and query result classes
* Requires PHP 5.3
*
* Events:
* - on_commit - Dispatched when the transaction is successfully committed to the DB
* - on_rollback - Dispatched when the transaction is rolled back in the DB
*
* #author Kenaniah Cerny <kenaniah#gmail.com>
* #version 1.1.2
* #license http://creativecommons.org/licenses/by/3.0/us/
* #copyright Copyright (c) 2009, Kenaniah Cerny
*/
class Database extends PDO {
private $stmt;
private $good_trans = null;
private $nested_transactions = 0; //Keeps track of virtual transaction nesting level
private $callbacks = array();
private static $connections = array(); //Keeps track of opened connections
/**
* Returns a database instance using lazy instantiation
* #param string $name a database connection name
* #param array $config database config details for a new connection
*/
static function getInstance($name = 'main', $config=array()){
//Attempt to return an existing connection
if(array_key_exists($name, self::$connections)):
return self::$connections[$name];
endif;
//Attempt to create a new connection
$host = in_array($config['host'], array('localhost', '127.0.0.1')) ? "" : ";host=" . $config['host'];
$db = new Database($config['driver'].":dbname=".$config['name'].$host, $config['user'], $config['pass']);
//Save to connection pool
self::$connections[$name] = $db;
return $db;
}
/**
* Registers a callback to be run when the given event is invoked
* #param string $event Event name
* #param callable $callable
*/
public function register_listener($event, $callable){
if(!array_key_exists($event, $this->callbacks)):
$this->callbacks[$event] = array($callable);
else:
$this->callbacks[$event][] = $callable;
endif;
}
/**
* Invokes callbacks for the given event type
* #param string $event Event name
* #param boolean $stop_on_false Stops bubbling this event if one of the handlers returns false
*/
protected function dispatch_event($event, $stop_on_false = true){
if(!array_key_exists($event, $this->callbacks)) return;
foreach($this->callbacks[$event] as $callable):
$res = call_user_func($callable, $this, $event);
if($stop_on_false && $res === false) return false;
endforeach;
return true;
}
/**
* PDO Constructor
* #param $dsn
* #param $username
* #param $password
*/
function __construct($dsn, $username, $password) {
parent::__construct($dsn, $username, $password);
}
/**
* Prepares an SQL statement
* #param string $sql
*/
function prepare($sql) {
$stmt = parent::prepare($sql, array(PDO::ATTR_STATEMENT_CLASS => array(__NAMESPACE__.'\DatabaseStatement')));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt;
}
/**
* Prepares an executes an SQL statement with the parameters provided
* #param string $sql
* #param array $params
*/
function execute($sql, $params = array()) {
if($this->debug):
var_dump("Statement:\n".$sql."\nParams: ".$this->fmt($params));
endif;
try {
$stmt = $this->prepare($sql);
$val = $stmt->execute((array) $params);
if($stmt->errorCode() != '00000') error_log($this->errormsg());
if($this->debug && $stmt->errorCode() != '00000'){
var_dump($stmt->errorInfo());
Errors::add("Database error: ".$this->errormsg(), E_USER_ERROR);
}
if(!$val) return false;
} catch (PDOException $e){
if($this->debug) var_dump($stmt->errorInfo());
error_log($this->errormsg());
Errors::add("Database error: ".$this->errormsg(), E_USER_ERROR);
if($this->nested_transactions) $this->failTrans();
else throw $e;
}
$this->stmt = $stmt;
return $stmt;
}
/**
* Returns the value of the first column of the first row
* of the database result.
* #param $sql
* #param $params
*/
function getOne($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getOne() : false;
}
/**
* Fetches a single column (the first column) of a result set
* #param $sql
* #param $params
*/
function getCol($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getCol() : false;
}
/**
* Fetches rows in associative array format
* #param $sql
* #param $params
*/
function getAssoc($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getAssoc() : false;
}
/**
* Fetches rows in array format with columns
* indexed by ordinal position
* #param $sql
* #param $params
*/
function getArray($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getArray() : false;
}
/**
* Fetches all rows in associative array format
* #param $sql
* #param $params
*/
function getAll($sql, $params = array()){
return $this->getAssoc($sql, $params);
}
/**
* Fetches rows in array format where the first column
* is the key name and all other columns are values
* #param $sql
* #param $params
*/
function getKeyPair($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getKeyPair() : false;
}
/**
* Fetches rows in multi-dimensional format where the first
* column is the key name and all other colums are grouped
* into associative arrays for each row
* #param $sql
* #param $params
*/
function getGroup($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getGroup() : false;
}
/**
* Fetches only the first row and returns it as an
* associative array
* #param $sql
* #param $params
*/
function getRow($sql, $params = array()){
$stmt = $this->execute($sql, $params);
return $stmt ? $stmt->getRow() : false;
}
/**
* Internal function used for formatting parameters in debug output
* #param unknown_type $params
*/
private function fmt($params){
$arr = array();
foreach((array) $params as $k=>$v){
if(is_null($v)) $v = "NULL";
elseif(is_bool($v)) $v = $v ? "TRUE" : "FALSE";
$arr[] = "[".$k."] => ".$v;
}
return "Array(".join(", ", $arr).")";
}
/**
* Returns the number of affected rows from an executed statement
*/
function affected_rows(){
return $this->stmt ? $this->stmt->rowcount() : false;
}
/**
* Automated statement processing
*
* Params array takes the following fields:
*
* - table The name of the table to run the query on
*
* - data A key-value paired array of table data
*
* - mode INSERT, UPDATE, REPLACE, or NEW
*
* - where Can be a string or key-value set. Not used on INSERTs
* If key-value set and numerically indexed, uses values from data
* If key-value and keys are named, uses its own values
*
* - params An array of param values for the where clause
*
* - returning Optional string defining what to return from query.
* Uses PostgreSQL's RETURNING construct
*
* This method will return either a boolean indicating success, an array
* containing the data requested by returning, or a boolean FALSE indicating
* a failed query.
*
*/
function autoExecute($table, $params, $data){
$fields = array(); //Temp array for field names
$values = array(); //Temp array for field values
$set = array(); //Temp array for update sets
$ins = array(); //Insert value arguments
$params['table'] = $table;
$params['data'] = $data;
$params['params'] = (array) $params['params'];
//Parse the data set and prepare it for different query types
foreach((array) $params['data'] as $field => $val):
$fields[] = $field;
$values[] = $val;
$ins[] = "?";
$set[] = $field . " = ?";
endforeach;
//Check for and convert the array/object version of the where clause param
if(is_object($params['where']) || is_array($params['where'])):
$clause = array();
$params['params'] = array(); //Reset the parameters list
foreach($params['where'] as $key => $val):
if(is_numeric($key)):
//Numerically indexed elements use their values as field names
//and values from the data array as param values
$field = $val;
$params['params'][] = $params['data'][$val];
else:
//Named elements use their own names and values
$field = $key;
$params['params'][] = $val;
endif;
$clause[] = $field . " = ?";
endforeach;
$params['where'] = join(" AND ", $clause);
endif;
//Figure out what type of query we want to run
$mode = strtoupper($params['mode']);
switch($mode):
case 'NEW':
case 'INSERT':
//Build the insert query
if(count($fields)):
$sql = "INSERT INTO " . $params['table']
. " (" . join(", ", $fields) . ")"
. " SELECT " . join(", ", $ins);
else:
$sql = "INSERT INTO " . $params['table']
. " DEFAULT VALUES";
endif;
//Do we need to add a conditional check?
if($mode == "NEW" && count($fields)):
$sql .= " WHERE NOT EXISTS ("
. " SELECT 1 FROM " . $params['table']
. " WHERE " . $params['where']
. " )";
//Add in where clause params
$values = array_merge($values, $params['params']);
endif;
//Do we need to add a returning clause?
if($params['returning']):
$sql .= " RETURNING " . $params['returning'];
endif;
//Execute our query
$result = $this->getRow($sql, $values);
//Return our result
if($params['returning']):
return $result;
else:
return $result !== false;
endif;
break;
case 'UPDATE':
if(!count($fields)) return false;
//Build the update query
$sql = "UPDATE " . $params['table']
. " SET " . join(", ", $set)
. " WHERE " . $params['where'];
//Do we need to add a returning clause?
if($params['returning']):
$sql .= " RETURNING " . $params['returning'];
endif;
//Add in where clause params
$values = array_merge($values, $params['params']);
//Execute our query
$result = $this->getRow($sql, $values);
//Return our result
if($params['returning']):
return $result;
else:
return $result !== false;
endif;
break;
case 'REPLACE': //UPDATE or INSERT
//Attempt an UPDATE
$params['mode'] = "UPDATE";
$result = $this->autoExecute($params['table'], $params, $params['data']);
//Attempt an INSERT if UPDATE didn't match anything
if($this->affected_rows() === 0):
$params['mode'] = "INSERT";
$result = $this->autoExecute($params['table'], $params, $params['data']);
endif;
return $result;
break;
case 'DELETE':
//Don't run if we don't have a where clause
if(!$params['where']) return false;
//Build the delete query
$sql = "DELETE FROM " . $params['table']
. " WHERE " . $params['where'];
//Do we need to add a returning clause?
if($params['returning']):
$sql .= " RETURNING " . $params['returning'];
endif;
//Execute our query
$result = $this->getRow($sql, $params['params']);
//Return our result
if($params['returning']):
return $result;
else:
return $result !== false;
endif;
break;
default:
user_error('AutoExecute called incorrectly', E_USER_ERROR);
break;
endswitch;
}
/**
* #see $this->startTrans()
*/
function beginTransaction(){
$this->startTrans();
}
/**
* Starts a smart transaction handler. Transaction nesting is emulated
* by this class.
*/
function startTrans(){
$this->nested_transactions++;
if($this->debug) var_dump("Starting transaction. Nesting level: " . $this->nested_transactions);
//Do we need to begin an actual transaction?
if($this->nested_transactions === 1):
parent::beginTransaction();
$this->good_trans = true;
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
endif;
}
/**
* Returns TRUE if the transaction will attempt to commit, and
* FALSE if the transaction will be rolled back upon completion.
*/
function isGoodTrans(){
return $this->good_trans;
}
/**
* Marks a transaction as a failure. Transaction will be rolled back
* upon completion.
*/
function failTrans(){
if($this->nested_transactions) $this->good_trans = false;
if($this->debug):
Errors::add("Database transaction failed: ".$this->errorMsg());
endif;
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
}
/**
* #see $this->rollbackTrans()
*/
function rollback(){
$this->rollbackTrans();
}
/**
* Rolls back the entire transaction and completes the current nested
* transaction. If there are no more nested transactions, an actual
* rollback is issued to the database.
*/
function rollbackTrans(){
if($this->nested_transactions):
$this->nested_transactions--;
if($this->debug) var_dump("Rollback requested. New nesting level: " . $this->nested_transactions);
$this->good_trans = false;
if($this->nested_transactions === 0):
$this->good_trans = null;
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
if($this->debug) var_dump("Transaction rolled back.");
parent::rollback();
$this->dispatch_event('on_rollback');
endif;
endif;
}
/**
* Clears the nested transactions stack and issues a rollback to the database.
*/
function fullRollback(){
while($this->nested_transactions) $this->rollbackTrans();
}
/**
* Returns the number of nested transactions:
* 0 - There is no transaction in progress
* 1 - There is one transaction pending
* >1 - There are nested transactions in progress
*/
function pending_trans(){
return $this->nested_transactions;
}
/**
* #see $this->completeTrans()
*/
function commit($fail_on_user_errors = false){
return $this->completeTrans($fail_on_user_errors);
}
/**
* Completes the current transaction and issues a commit or rollback to the database
* if there are no more nested transactions. If $fail_on_user_errors is set, the
* transaction will automatically fail if any errors are queued in the Errors class.
* #param boolean $fail_on_user_errors
*/
function completeTrans($fail_on_user_errors = false){
if(!$this->nested_transactions) return;
//Fail the transaction if we have user errors in the queue
if($fail_on_user_errors && Errors::exist()) $this->good_trans = false;
//Do we actually need to attempt to commit the transaction?
if($this->nested_transactions === 1):
if(!$this->good_trans || !parent::commit()){
if($this->debug) var_dump("Transaction failed: " . $this->errormsg());
$this->rollbackTrans();
return false;
}
//Transaction was good
$this->nested_transactions--;
$this->good_trans = null;
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
if($this->debug) var_dump("Transaction committed.");
$this->dispatch_event('on_commit', false);
return true;
else:
//Don't take action just yet as we are still nested
$this->nested_transactions--;
if($this->debug) var_dump("Virtual commit. New nesting level: " . $this->nested_transactions);
endif;
return $this->good_trans;
}
/**
* Returns the text of the most recently encountered error
*/
function errormsg(){
$msg = $this->errorInfo();
return $msg[2];
}
}
class DatabaseStatement extends \PDOStatement implements \Countable {
/**
* Binds passed parameters according to their PHP type and executes
* the prepared statement
*/
function execute($params = array()) {
$i = 1;
foreach($params as $k => $v):
$mode = PDO::PARAM_STR;
if(is_null($v)) $mode = PDO::PARAM_NULL;
elseif(is_bool($v)) $mode = PDO::PARAM_BOOL;
elseif(is_resource($v)) $mode = PDO::PARAM_LOB;
$this->bindParam($i, $params[$k], $mode);
$i++;
endforeach;
$ok = parent::execute();
return $ok ? $this : false;
}
/**
* Returns the value of the first column of the first row
*/
function getOne() {
return $this->fetchColumn(0);
}
/**
* Returns an array of values of the column found at $index
* position.
* #param $index
*/
function getCol($index=0) {
return $this->fetchAll(PDO::FETCH_COLUMN, $index);
}
/**
* Returns all rows in numeric array format
*/
function getArray(){
return $this->fetchAll(PDO::FETCH_NUM);
}
/*
* Returns all rows in associative array format
*/
function getAll(){
return $this->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Returns all rows in associative array format
*/
function getAssoc() {
return $this->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Returns rows in multi-dimensional format where the first
* column is the key name and all other colums are grouped
* into associative arrays for each row
*/
function getGroup() {
return $this->fetchAll(PDO::FETCH_GROUP);
}
/**
* Returns a single row in associative format
*/
function getRow(){
return $this->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetches rows in array format where the first column
* is the key name and all other columns are values
*/
function getKeyPair(){
//Emulate it
$tmp = $this->fetchAll(PDO::FETCH_ASSOC);
$arr = array();
for($i = 0; $i < count($tmp); $i++){
$arr[array_shift($tmp[$i])] = count($tmp[$i]) > 1 ? $tmp[$i] : array_shift($tmp[$i]);
}
return $arr;
}
/**
* Returns the number of rows returned by this statement
*/
function recordCount(){
return $this->rowCount();
}
/**
* Returns the number of rows returned by this statement
*/
function count(){
return $this->rowCount();
}
}
Even though my DB class does not use prepared statements I still want to mention it here. I see no reason at all to implement everything with prepared statements. I do know that prepared statements are faster, but only when used multiple times. If you execute the query only once (and this is the only type of query I normally need to use), it is slower. Thus it is counterproductive to use prepared statements everywhere.
Proper description of the class may be found some place else at stackoverflow. But here some of the good stuff:
Less then 100 lines database layer
DB::x for DB::instance()->execute and DB::q for DB::instance()->query
autoQuoting with two types of placeholders ? and ?x (where x may be ,, & and |). The ?, placeholder may be used as an UPDATE helper here.
But for full information see the stackoverflow post linked above ;)
PS: The README in the repo does not apply to this class. It is for the normal DB.php, not for DB_intelligent.php.
PPS: The class is written for PHP 5.3. If you want to use it on PHP 5.2 simply copy all those PDO methods from DB_forPHP52.php to DB_intelligent.php and remove the __callStatic method.
Just in addition to other answers: a method for proper quote of column names:
/**
* Escape identifier (database/table/column name) - ie. if you're using MySQL:
* db_name.tbl_name.col_name -> `db_name`.`tbl_name`.`col_name`
**/
protected function quoteIdentifier($identifier) {
static $escapeChars = array(
'mysql' => '``',
'oracle' => '""',
'mssql' => '[]',
//...
);
$escape = $escapeChars[$this->getAttribute(self::ATTR_DRIVER_NAME)];
$identifier = (array) explode('.', $identifier);
$identifier = array_map(function($segment) use($escape) {
return $escape[0] . $segment . $escape[1];
}, $identifier);
return implode('.', $identifier);
}
You can extend PDO like that:
class CustomPDO extends PDO {
public function updateTable($sTable, array $aValues = array()){
if (!empty($aValues) && !empty($sTable)){
# validation of table / columns name
$sTable = mysql_real_escape_string($sTable);
$aColumns = array_map('mysql_real_escape_string',array_keys($aValues));
$aElements = array();
foreach ($aColumns as $sColumn){
$aElements[] = "`$sColumn`= :$sColumn";
} // foreach
$sStatement = "UPDATE $sTable SET " . implode(',', $aElements);
$oPDOStatement = $this->prepare($sStatement);
if ($oPDOStatement){
return $oPDOStatement->execute($aValues);
} // if
} // if
return false;
} // updateTable
}
# usage :
# $oDb->updateTable('tbl_name',$_POST);
# test
error_reporting (E_ALL);
ini_Set('display_errors',1);
$oDb = new CustomPDO('sqlite::memory:');
$oDb->exec('CREATE TABLE t1(c1 TEXT, c2 INTEGER)');
$oDb->exec("INSERT INTO t1(c1, c2) VALUES ('X1',1)");
var_dump($oDb->query('SELECT * FROM t1')->fetchAll(PDO::FETCH_ASSOC));
$oDb->updateTable('t1', array('c1'=>'f1','c2**2'=>2));
var_dump($oDb->query('SELECT * FROM t1')->fetchAll(PDO::FETCH_ASSOC));
Like others I've extended the standard PDO class to suit my needs. Something along the lines of this may suit you:
Class ExtendedPDO extends PDO
{
public function prepareArray($sql, array $data)
{
// Call the standard prepare method
$statement = parent::prepare($sql);
foreach ($data as $field=>$value) {
$statement->bindValue(':' . $field, $value);
}
return $statement;
}
}
Then you can use it quite simply:
// Include connection variables
include '../includes/config/database.php';
// The data to use in the query
$data = array(
'title' => 'New value',
'id' => 1,
);
// The query you want to run
$sql = '
UPDATE
test
SET
title = :title
WHERE
id = :id
';
try {
// Connect to the database
$dbh = new ExtendedPDO(PDO_DSN, PDO_USERNAME, PDO_PASSWORD);
// Attach the data to your query
$stmt = $dbh->prepareArray($sql, $data);
// Run it
$stmt->execute();
} catch (PDO Exception $e) {
echo $e->getMessage();
}
Insert queries often require many placeholders. The question mark style is then hard to read, and named parameters are repetitive and prone to typing errors. So, I created a function for the whole insert query:
function insert($table, $col_val){
global $db;
$table = preg_replace('/[^\da-z_]/i', '', $table);
$smt = $db->prepare("DESCRIBE `$table`");
$smt->execute();
$columns = $smt->fetchAll(PDO::FETCH_COLUMN);
$sets = array();
$exec = array();
foreach($col_val as $col => $val){
if(!in_array($col, $columns))
return false;
$sets[] .= "`$col`=?";
$exec[] = $val;
}
$set = implode(',', $sets);
$smt = $db->prepare("INSERT INTO `$table` SET $set");
$smt->execute($exec);
return $db->lastInsertId();
}
Usage is simple:
insert('table_name', array(
'msg' => 'New message',
'added' => date('Y-m-d H:i:s'),
));
And if you need lastInsertId():
$new_id = insert(...
Reference: How can I prevent SQL injection in PHP?
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');
$preparedStatement->execute(array(':name' => $name));
$rows = $preparedStatement->fetchAll();

Categories