BeginTransaction can not work in PHP mysql - php

I want to insert data into CLOUD and IDC tables.
Cloudid is the foreign key of IDC table, so i want to use transaction.
Before $conn->beginTransaction(); and $conn->commit(); are added ,it works fine, but without them, it works fine.
Here is my code:
<?php
if($_GET["act"]=="add")
{
try
{
$conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxxx');
//$conn->beginTransaction();
$query="
insert into CLOUD (name,date) VALUES('".$_POST['customerName']."','".$_POST['firstDay']."');
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName3']."','".$_POST['engID3']."','".$_POST['engPhone3']."',LAST_INSERT_ID());
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName4']."','".$_POST['engID4']."','".$_POST['engPhone4']."',LAST_INSERT_ID());
";
$stmt=$conn->query($query);
//$conn->commit();
echo "success";
}
catch(PDOException $e)
{
$conn->rollBack();
echo "connect failed!".$e->getMesage();
exit;
}
}
?>

Transactions are only available when the database uses InnoDB as the storage engine. You are probably using MyISAM
Have a look here for more details on the difference between the storage engines https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html
As a side note, your code is vulnerable to SQL injections because you use raw post data in non prepared queries. you should have a look there : How can I prevent SQL injection in PHP?

Try to initiate your connection and get last inserted id like below, also i would recommend you to use prepared statements (see http://php.net/manual/ru/pdo.prepare.php):
if($_GET["act"]=="add")
{
try {
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=xxx', 'root', 'xxx',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->beginTransaction();
$stmt = $dbh->prepare('insert into CLOUD (name,date) VALUES(:customerName,:firstDay)');
$stmt->execute([
'customerName' => $_POST['customerName'],
'firstDay' => $_POST['firstDay']
]);
$cloud_id = $dbh->lastInsertId();
$stmt = $dbh->prepare('insert into IDC (name,id,phone,cloudid) VALUES(:name,:id,:phone,:cloudid)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':cloudid', $cloud_id);
$name = $_POST['engName3'];
$id = $_POST['engID3'];
$phone = $_POST['engPhone3'];
$stmt->execute();
$name = $_POST['engName4'];
$id = $_POST['engID4'];
$phone = $_POST['engPhone4'];
$stmt->execute();
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
echo "Failed: " . $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

PDO : Need to escape string or not ?

I use this code to insert some data into my database.
I adapt my previous code based on mysqli to use PDO now.
For the 2 parameters name and id, do i need to escape them using a function like mysqli_real_escape_string with PDO ? or is it OK to pass these params direclty in the query ?
<?php
try
{
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$id = $json["id"]
$name = $json["name"]
$pdo->beginTransaction();
// do request
$pdo->query('INSERT INTO test(id, name) VALUES ('$id', '$name')');
$pdo->commit();
echo 'Everything is OK';
}
catch(Exception $e)
{
$pdo->rollback();
echo 'An error occurred :<br />';
echo 'Error : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
exit();
}
You need to prepare your statement, try this:
$query = $pdo->prepare('INSERT INTO test(id, name) VALUES (:theid, :thename)');
$query->execute(array(
'theid' => $id,
'thename' => $name
));
You don't have to escape strings but you have to use preared statements.
Here is what your code should be.
<?php
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$pdo->prepare('INSERT INTO test(id, name) VALUES (:id,:name)')->execute($json);
echo 'Everything is OK';
note that a transaction is useless for just a single query and the way you are reporting errors is wrong.
also, if $json already contains the all the data for thequery, no need to store its contents in separate variables.
It's not okay. You need to use prepared statements or PDO::quote().

PHP PDO query on MySQL does not return as expected

I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);

Insert data to mysql doesn't work from php

I have the following PHP code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
typeID => is number, the other values are text.
There is no error in this code, but the insert query doesn't work (I have no idea why because I don't get any error message).
How can I fix it?
There are a number of problems with your code.
It's open to SQL injectoion
mysql_* functions have been deprecated
This code is untested but should give you an idea:
try
$dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
$sth->execute($_POST);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
Have a look at this article on Why you Should be using PHP’s PDO for Database Access
Try this
if(isset($_POST[articleTitle])) {
$insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories