PDO Multi-query "SQLSTATE[HY000]: General error" - php

I'm still learning PDO so I might of missed something but basically I'm trying to insert a row into a table and then select the generated id.
I'm not sure if it likes both queries in one pdo statement. Here is the code I'm using to execute the SQL.
public function ExecuteQuery($sql, $params = array())
{
if($this->_handle == null)
$this->Connect();
$query = $this->_handle->prepare($sql);
foreach($params as $key => $value)
{
if(is_int($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_INT);
}else if(is_bool($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_BOOL);
}else if(is_null($value)){
$query->bindValue(':'.$key, $value, \PDO::PARAM_NULL);
}else{
$query->bindValue(':'.$key, $value, \PDO::PARAM_STR);
}
}
$query->execute();
$x = $query->fetchAll(\PDO::FETCH_ASSOC);
var_dump($x);
return $x;
}
This function is part of a database class, $this->_handle is the PDO object.
public function Connect()
{
try {
$this->_handle = new \PDO('mysql:host='.$this->_host.';dbname='.$this->_database, $this->_username, $this->_password);
$this->_handle->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
And the SQL I'm running is this:
INSERT INTO `users` (`Username`, `Password`, `PasswordSalt`, `Email`, `IsAdmin`, `LoginAttempts`, `LastLogin`, `LastLoginAttempt`, `Created`) VALUES (:username, :password, :passwordsalt, :email, :isadmin, :loginattempts, :lastlogin, :lastloginattempt, :created); SELECT LAST_INSERT_ID() as 'id'
The user is created and is there in the users table but it errors after that.
Can anyone see what am doing wrong? :)
Cheers!

I'm pretty sure the mysql driver for PDO (maybe mysql itself?) does not support multi-query prepared statements.
Instead of SELECT LAST_INSERT_ID() in your query, use Conexion::$cn->lastInsertId() after your $query->execute()

I think this is correct:
function ExecuteQuery($sql, $params = array())
{
if(Conexion::$cn== null)
Conexion::Connect();
$paramString="";
foreach($params as $k=>$v)
{
$param = " :".$k." ,";
$paramString .= $param;
}
$sql.=substr($paramString,0,-2);
$query = Conexion::$cn->prepare($sql);
foreach($params as $key => $value)
{
echo "entro";
$query->bindParam(":".$key, $value);
}
$query->execute();
$x = $query->fetchAll(\PDO::FETCH_ASSOC);
var_dump($x);
return $x;
}
public function Connect()
{
try {
$dns='dblib:host='.Conexion::$server.";dbname=".Conexion::$db.";";
Conexion::$cn = new \PDO($dns, Conexion::$user, Conexion::$passw);
Conexion::$cn->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

Related

MySQL transaction, rollback doesn't work, (PHP PDO)

I have a loop that inserts data in two tables, in the first iteration of the loop the insert is succesfull, but in the second iteration the insert will fail.
I have written the script so that if any of the iterations fail, the entire transaction should be rollbacked. However, this doesn't work.
The first iteration (that succeeded) isn't rolled back...
<?php
include('model/dbcon.model.php');
$languages = array('project_nl', 'project_en');
DBCon::getCon()->beginTransaction();
$rollback = true;
foreach($languages as $language) {
$Q = DBCon::getCon()->prepare('INSERT INTO `'.$language.'`(`id`, `name`, `description`, `big_image`) VALUES (:id,:name,:description,:big_image)');
$Q->bindValue(':id', '1', PDO::PARAM_INT);
$Q->bindValue(':name', 'test', PDO::PARAM_INT);
$Q->bindValue(':description', 'test', PDO::PARAM_INT);
$Q->bindValue(':big_image', 'test', PDO::PARAM_INT);
try {
$Q->execute();
} catch (PDOException $e) {
$rollback = true;
}
}
if ($rollback) {
echo 'rollbacking...';
DBCon::getCon()->rollBack();
} else {
echo 'commiting...';
DBCon::getCon()->commit();
}
?>
Why isn't the entire transaction rolled back?
Thanks in advance.
Either auto-commit is enabled, or the connection is not persisting, or you're not using innodb.
This will work, which means DBCon::getCon() is not doing what you think it's doing.
<?php
include('model/dbcon.model.php');
$languages = array('project_nl', 'project_en');
$connection = DBCon::getCon();
$connection->beginTransaction();
$rollback = true;
foreach($languages as $language) {
$Q = $connection->prepare('INSERT INTO `'.$language.'`(`id`, `name`, `description`, `big_image`) VALUES (:id,:name,:description,:big_image)');
$Q->bindValue(':id', '1', PDO::PARAM_INT);
$Q->bindValue(':name', 'test', PDO::PARAM_INT);
$Q->bindValue(':description', 'test', PDO::PARAM_INT);
$Q->bindValue(':big_image', 'test', PDO::PARAM_INT);
try {
$Q->execute();
} catch (PDOException $e) {
$rollback = true;
}
}
if ($rollback) {
echo 'rollbacking...';
$connection->rollBack();
} else {
echo 'commiting...';
$connection->commit();
}
?>

PDO multi insert statement

I've got a working insert for a single input field but when I try to add a couple more it seems to break everything. I have a database connection working fine and including that correctly at the top of the page when I change the "isset" to have the 3 columns it breaks.
This is my set statement;
if(isset($_POST['title, question, tags']))
{
$success = insertData('questions', 'title', $_POST['title']);
$success = insertData('questions', 'question', $_POST['question']);
$success = insertData('questions', 'tags', $_POST['tags']);
if(!$success)
echo 'Sorry failed :(';
}
The function I call from a functions php file;
function insertData($tablename, $columnName, $value)
{
$sql = 'INSERT into '.$tablename.'('.$columnName.') VALUES(:Value)';
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
$statement->bindValue(":Value", $value, PDO::PARAM_STR);
$bReturn = false;
try
{
$statement->execute();
$bReturn = true;
}
catch(PDOExecption $e)
{
echo $e->getMessage();
}
return $bReturn;
}
Does anyone know where I'm going wrong here?
if(isset($_POST['title, question, tags']))
Is not correct syntax
instead You can do:
if(isset($_POST['title']) && isset($_POST['question']) && isset($_POST['tags']))
or even
if(isset($_POST['title'], $_POST['question'], $_POST['tags']))
It would be easier to do execute it without binding:
insertData
function insertData($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',', array_fill(0, count($params), '?'));
$sql_string = "INSERT INTO {$tablename} ({$columnString}) VALUES ({$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql_string);
//execute query
$success = $statement->execute(array_values($params));
//return boolean success
return $success;
}
But If you really need to bind, you can do it the following way:
function insertDataBind($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',:', array_keys($params));
$sql_string = "INSERT INTO {$tablename} ({$column_string}) VALUES (:{$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
//bind
foreach($params as $key=>$value){
$statement->bindValue($key, $value);
}
//execute query
$success = $statement->execute();
//return boolean success
return $success;
}
usage:
if(isset($_POST['title'], $_POST['question'], $_POST['tags'])){
$params = array('title' => $_POST['title'],
'question'=>$_POST['question'],
'tags'=>$_POST['tags']
);
$success = insertData('questions', $params);
if(!$success)
echo 'Sorry failed :(';
}

How do you perform a dynamic php, PDO prepared statement Update?

I'm having trouble finding good documentation on pdo update prepared statements and even more trouble finding documentation on dynamically updating the database with pdo prepared statements. I've gotten my dynamic insert to work but am having trouble with the update. The error I'm getting is:
Warning: PDOStatement::execute() [pdostatement.execute]:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
in
/Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php
on line 91 error
Here is the class I created minus a couple of methods that are irrelevant to this problem:
<?php
require_once("../config/main.php");
class Database{
protected static $dbFields = array('username', 'password');
public $db;
public $tableName = 'users';
public $id = 1;
public $username = "Jonny";
public $password = "Appleseed";
public function __construct() {
$this->connect();
}
public function connect(){
try {
$this->db = new PDO("mysql:host=".DB_SERVER."; dbname=".DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function properties() {
$properties = array();
foreach (self::$dbFields as $field) {
if (isset($this->field) || property_exists($this, $field)) {
$properties[$field] = $this->$field;
}
}
return $properties;
}
public function propertyValues() {
$property = $this->properties();
$propertyValues = array();
foreach ($property as $key => $value) {
$propertyValues = ":" . implode(", :", array_keys($property));
}
return $propertyValues;
}
public function polishedVals(){
// The end result of this function is:
// username=:username, password=:password
$props = $this->properties();
$phaseOne = array();
foreach ($props as $key => $value) {
$phaseOne[$key] = ":".$key;
}
$phaseTwo = array();
foreach ($phaseOne as $key => $value) {
$phaseTwo[] = "{$key}={$value}";
}
$polishedVals = implode(", ", $phaseTwo);
return $polishedVals;
}
public function update(){
$stmt = "UPDATE ". $this->tableName." SET ";
$stmt .= $this->polishedVals();
$stmt .= "WHERE id=" . $this->id;
$stmt = $this->db->prepare($stmt);
if($stmt->execute($this->properties())) {
echo "yes";
} else {
echo "error ";
}
}
}
$database = new Database();
echo$database->update();
?>
With all the variables replaced with the actual values, the result I'm going for with the update() method would look like this:
public function update(){
$stmt = "UPDATE users SET ";
$stmt .= "username=:username, password=:password ";
$stmt .= "WHERE id=1";
$stmt = $this->db->prepare($stmt);
if($stmt->execute($this->properties())) {
echo "yes";
} else {
echo "error ";
}
}
In addition to spotting this problem, please let me know if you see any other issues with this code. I'm still kind of new to PHP.
Edit: I've now created a new method that adds a : to the beginning of each key in the properties array:
public function colProperties(){
$properties = $this->properties();
$withCols = array();
foreach($properties as $key => $value){
$withCols[":".$key] = $value;
}
return $withCols;
}
So my update() method now looks like:
public function update(){
$stmt = "UPDATE ". $this->tableName." SET ";
$stmt .= $this->polishedVals();
$stmt .= "WHERE id=" . $this->id;
$stmt = $this->db->prepare($stmt);
if($stmt->execute($this->colProperties())) {
echo "yes";
} else {
echo "error ";
}
}
and if I var_dump($this->colProperties) I get:
array(2) { [":username"]=> string(5) "Jonny" [":password"]=> string(9) "Appleseed" }
And still getting the same error.
I don't think that passing parameters to an UPDATE query requires a different method than a SELECT one. The information in the PDOStatement->execute() manual page should apply:
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>
You are using named parameters so execute() expects an associative array. Use var_dump() to display $this->properties() right before execute():
var_dump($this->properties())
Make sure you keys match exactly.
The error is that in between
$stmt .= $this->polishedVals();
$stmt .= "WHERE id=" . $this->id;
There needs to be a space in between the WHERE clause as the polishedVals() method does not add a space after the implode. So, you'll have something like
UPDATE User SET city=:city, location=:locationWHERE User.id=28
Which causes the error.
Simple bug.

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;
}

help with making this mysql query into a PDO query

I have been using this for a while, but have since then upgraded to PDO instead of mysql queries. But I can't seem to get this particular snippet to work at all.
$query = mysql_query ($sql) or die (mysql_error());
while ($records = #mysql_fetch_array ($query)) {
$alpha[$records['alpha']] += 1;
${$records['alpha']}[$records['id_clients']] = array(
$records['first_name'], //item[0]
);
}
I have tried this
while ($records = $this->db->fetch_row_assoc($sql)) {
$alpha[$records['alpha']] += 1;
${$records['alpha']}[$records['id_clients']] = array(
$records['first_name'], //item[0]
);
}
and my PDO code is
public function query($statement)
{
return self::$PDO->query($statement);
}
public function fetch_row_assoc($statement) {
self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try
{
$stmt = self::$PDO->query($statement);
$result = $stmt->fetch();
return $result;
}catch(PDOException $e){
echo $e->getMessage();
}
return false;
//return self::$PDO->query($statement)->fetch(PDO::FETCH_ASSOC);
}
The query function works, but I have introduced my fetch_row_assoc function in hopes that I can do that same thing with mysql_fetch_asso.
$sql = "SELECT
SUBSTRING(`last_name`, 1, 1) AS alpha,
SUBSTRING(`middle_name`, 1, 1) AS subMiddleName,
`id_clients`,
`type`,
`first_name`,
`middle_name`,
`last_name`,
`address`,
`primary_number`,
`secondary_number`,
`home_number`,
`office_number`,
`cell_number`,
`fax_number`,
`ext_number`,
`other_number`,
`comments`
FROM `clients`
WHERE `user_id` = 1
AND `is_sub` = 0
AND `prospect` = 1
ORDER BY `last_name`";
Try this:
public function query($statement)
{
return self::$PDO->query($statement);
}
public function fetch_row_assoc($statement) {
self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try
{
$stmt = self::$PDO->query($statement);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetch();
return $result;
}catch(PDOException $e){
echo $e->getMessage();
}
return false;
}

Categories