PDO with Mulitple Update prepared statements failing to execute - php

I am trying to construct a PDO multiple prepared statement that updates 2 tables.
I am having trouble and getting various errors when I try to get my code working, the latest: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
When looking on SO I have found various ways of doing this, however I can't figure out how to implement them.
Another concern is not being able use $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);. I've read online that is import to include for security. However I also understand that it doesn't work with Multi Queries PDO (?).
It is possible to do a Multi Update or should I have different scripts?
(Also is my code secure from SQL Injection?)
This is the Code I am working with:
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=*', '*', '*');
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$est_id = $_POST['est_id'];
$known_for = $_POST['known_for'];
$street_address = 'addressToAdd';
$sql = " UPDATE `theList`
SET `known_for` = :known_for
WHERE `id` = :est_id
";
$sql = " UPDATE `est_address`
SET `street_address` = :street_address
WHERE `id` = :est_id
";
$params = array(
':est_id' => $est_id,
':known_for' => $known_for,
':street_address' => $street_address
);
$statement = $conn->prepare($sql);
$statement->execute($params);
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=*', '*', '*');
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$est_id = $_POST['est_id'];
$known_for = $_POST['known_for'];
$street_address = 'addressToAdd';
$sqlKnown = "UPDATE `theList` SET `known_for` = :known_for WHERE `id` = :est_id";
$stKnown = $conn->prepare( $sqlKnown );
$stKnown->execute([
':est_id' => $est_id,
':known_for' => $known_for,
]);
$sqlStreet = "UPDATE `est_address` SET `street_address` = :street_address WHERE `id` = :est_id";
$stStreet = $conn->prepare( $sqlStreet );
$stStreet->execute([
':est_id' => $est_id,
':street_address' => $street_address
]);
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

Related

Pdo Transaction does not roll back when while DELETE did not execute

I am building am app that should execute multiple queries that involve insert, delete and update commands. There is no syntax error but I discovered that the delete command did not delete entry but the insert command inserted row and the action did not rollback. If the delete action did not happen, insert and others should be cancelled is the desired result.
<?
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->beginTransaction();
$D = 2;
$Dn = 3;
$dumpi = $pdo->prepare("INSERT INTO `dumpi` .... SELECT .... FROM .... ");
$dumpi->execute();
$matchi = $pdo->prepare("DELETE FROM `marchi` WHERE `id`=....");
$matchi->execute();
$usri = $pdo->prepare("UPDATE `users` SET `status`='0' WHERE `id`='$Dn' ");
$usri->execute();
$donati = $pdo->prepare("UPDATE `dnsn` SET `status`='d' WHERE `id`='$D' ");
$donati->execute();
$donatidel = $pdo->prepare("UPDATE `dnsn` SET `status`='d',`deleted_by`='m' WHERE `dn`='$Dn' AND `status`='1' ");
$donatidel->execute();
$navwal = $pdo->prepare("UPDATE `wlt` SET `status`='0' WHERE `user`='$Dn'");
$navwal->execute();
$navwalt = $pdo->prepare("UPDATE `wlt` SET `status`='0' WHERE `dn`='$Dn' ");
$navwalt->execute();
// dont let te $D and Dn confuse you, its not the one causing any error
$pdo->commit();
// echo 'it works';
} catch (PDOException $e) {
$pdo->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
The code ended here...
my connection to Db is of this script here...(just added for ref. php7)
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => true);
try {
$pdo = new PDO(
"mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
MYSQL_USER, //Username
MYSQL_PASSWORD, //Password
$pdoOptions //Options
);} catch (Exception $e) {
// design this well to make sense
die(
// conmment out in launch
$e->getMessage())
);
}
Well, if a query do not find any data, it is not an error.
If it's important for you that the delete query should necessarily find the the record to delete, then you have to verify that manually and than throw an exception.
$stmt = $pdo->prepare("DELETE FROM `marchi` WHERE `id`=?");
$stmt->execute([....]);
if (!$stmt->rowCount())
{
throw new Exception("Delete didn't find a record")
}
And then catch Exception, not PDOException.
Note that for some reason you aren't using prepared statements while you should

Windows Azure MaxSizeInByte Statement

i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>

PHP PDO - Multiple Inserts in one PDO Prepare doesn't catch errors

I'm passing multiple INSERT statements in one PDO prepare statement and the execute works; however, if any of the inserts fail the the execute() always returns TRUE and catch() is never invoked.
$query = '
INSERT INTO resources SET
resource_type_id = :audio_resource_type_id
, resource_status_id = :resource_status_id
, is_hosted = :is_hosted
, category_id = :category_id
, serve_url = :audio_serve_url
, title = :title;
SET #audio_id = LAST_INSERT_ID();
INSERT INTO resources SET
resource_type_id = :thumbnail_resource_type_id
, resource_status_id = :resource_status_id
, category_id = :category_id
, serve_url = :thumbnail_serve_url
, parent_resource_id = #audio_id;';
if ($audio_duration) {
$query .= '
INSERT INTO audio_duration SET
audio_id = #audio_id
, duration_seconds = :audio_duration';
}
try {
$sth = $dbi->dbh->prepare($query);
$sth->bindParam('audio_resource_type_id', $this->resource_types['audio']);
$sth->bindParam('thumbnail_resource_type_id', $this->resource_types['THUMBNAIL']);
$sth->bindParam('resource_status_id', $resource_status_id);
$sth->bindParam('category_id', $this->category_id);
$sth->bindParam('audio_serve_url', $audio_serve_url);
$sth->bindParam('thumbnail_serve_url', $thumbnail_serve_url);
$sth->bindParam('title', $title);
$sth->bindParam('audio_duration', $audio_duration);
$sth->execute();
} catch (PDOException $e) {
print "Error!: " . $e->getMessage();
log($e->getMessage());
alert($e->getMessage());
return FALSE;
}
Thank you for any thoughts on this.
Just want to point out this..
To stop PDO from silently failing, you can set the error mode on the PDO connection.
$dbh = new PDO();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
There is also PDO::ERRMODE_WARNING if you want errors but still continue.

MySQL MATCH, AGAINST not works with PDO

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Categories