note 125581 added to class.pdostatement
| From: | nmurzin.mail.ru via php-notes | Date: | Wed, 09 Dec 2020 08:22:27 +0000 |
| Subject: | note 125581 added to class.pdostatement | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-215954@lists.php.net to get a copy of this message | ||
I think I found a way to execute a protected SQL query and at the same time find out the number of
affected records.
I have the table 'tbl_users' with the following fields: id, login, password, age
<?
const DB_DRIVER = "mysql";
const DB_HOST = "localhost";
const DB_NAME = "my_db_name";
const DB_LOGIN = "root";
const DB_PASS = "root"; //OpenServer.
$connectionString = DB_DRIVER.':host='.DB_HOST.';dbname='.DB_NAME;
try
{
//Connect to database.
$db = new PDO($connectionString, DB_LOGIN, DB_PASS);
}
catch(PDOException $e)
{
die("Error: ".$e->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
//Decreasing age for user 'nick1'.
$prep1 = $db->prepare("UPDATE tbl_users SET age=age-1 WHERE login='nick1'");
//Increasing age for user 'nick2'.
$prep2 = $db->prepare("UPDATE tbl_users SET \r\n age=age+1 WHERE
login='nick2'");
//Start transaction.
$db->beginTransaction(); //Table type must be InnerDB!
//We assume that everything will be fine.
$flagDone = true;
//The exec() method returns the number of rows affected by the query.
//$prep1->queryString is already an escaped SQL string.
$result = $db->exec($prep1->queryString);
if($result==false || $result!=1) //var_dump($result) - int(1) or bool(false).
$flagDone = false;
$result = $db->exec($prep2->queryString);
if($result==false || $result!=1)
$flagDone = false;
if($flagDone)
{
if($db->commit())
echo "Transaction was successful";
}
else{
echo "Transaction fail";
$db->rollback();
}
echo "<br>";
}
catch(PDOException $e)
{
die("Error: ".$e->getMessage());
}
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.244 (proxied: 188.246.168.129)
----
Manual Page -- http://php.net/manual/en/class.pdostatement.php
Edit -- https://master.php.net/note/edit/125581
Del: integrated -- https://master.php.net/note/delete/125581/integrated
Del: useless -- https://master.php.net/note/delete/125581/useless
Del: bad code -- https://master.php.net/note/delete/125581/bad+code
Del: spam -- https://master.php.net/note/delete/125581/spam
Del: non-english -- https://master.php.net/note/delete/125581/non-english
Del: in docs -- https://master.php.net/note/delete/125581/in+docs
Del: other reasons-- https://master.php.net/note/delete/125581
Reject -- https://master.php.net/note/reject/125581
Search -- https://master.php.net/manage/user-notes.php