How to handle PDO exceptions [duplicate] - php

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

Related

How can I convert this mysqli to PDO?

<?php
require_once('dbconfig.php');
global $con;
$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
You should use ->bindColumn Manual
See also This answer.
Best Practise: Do not use SELECT * instead define each column you need to grab from the table.
Do not globalise your connection variable. This is a security risk as well as adding bloat and should be unneeded on your code.
Because it is a static statement you can use ->query rather than prepare, as nothing needs to be prepared.
Solution:
$query = $con->query("SELECT id,name,username,password FROM userinfo ORDER BY id DESC");
try {
$query->execute();
$query->bindColumn(1, $id);
$query->bindColumn(2, $name);
$query->bindColumn(3, $username);
$query->bindColumn(4, $password);
}
catch (PDOException $ex) {
error_log(print_r($ex,true);
}
Alternatively:
A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement. From the manual
foreach ($conn->query('SELECT id,name,username,password FROM userinfo ORDER BY id DESC') as $row) {
print $row['id'] . " is the ID\n";
print $row['name'] . " is the Name\n";
print $row['username'] . " is the Username\n";
}
See Also:
Mzea Has some good hints on their answer, you should use their $options settings as well as using their suggested utf8mb4 connection character set.
And their suggestion for using ->fetchAll is also completely valid too.
Try this
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Something weird happened'); //something a user can understand
}
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);

php transaction error, i always get a rollback error [duplicate]

This question already has answers here:
PHP PDO - There is no active transaction
(2 answers)
Closed 2 years ago.
im trying to update 2 tables at once. from my research i have to use a transaction for this:
protected function myUpdateFunction(){
try{
$this->connect()->beginTransaction();
$itemID = filter_input(INPUT_POST, 'updateItemID');
$itemName = filter_input(INPUT_POST, 'updateItemName');
$itemDescription = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice = filter_input(INPUT_POST, 'updateItemPrice');
$itemStock = filter_input(INPUT_POST, 'updateItemStock');
$updateItemBtn = filter_input(INPUT_POST, 'updateItemBtn');
$sql = "UPDATE oopphp_items SET itemName = ?, itemDescription = ?, itemPrice = ?, itemStock = ? WHERE itemID = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice, PDO::PARAM_STR);
$stmt->bindParam(4, $itemStock, PDO::PARAM_INT);
$stmt->bindParam(5, $itemID, PDO::PARAM_INT);
$stmt->execute();
//wishlist
$itemID_fk = filter_input(INPUT_POST, 'updateItemID');
$itemName_fk = filter_input(INPUT_POST, 'updateItemName');
$itemDescription_fk = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice_fk = filter_input(INPUT_POST, 'updateItemPrice');
$sql = "UPDATE oopphp_wishlist SET itemName_fk = ?, itemDescription_fk = ?, itemPrice_fk = ? WHERE itemID_fk = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName_fk, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription_fk, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice_fk, PDO::PARAM_STR);
$stmt->bindParam(4, $itemID_fk, PDO::PARAM_INT);
$stmt->execute();
$this->connect()->commit();
}
catch(Exception $e){
echo $e->getMessage();
$this->connect()->rollBack();
}
}
i get the following error:
Fatal error: Uncaught PDOException: There is no active transaction
when i tried looking for answers they all said to put it inside a try-catch, which i already did. all examples i could find do it like this. as seen here: PHP PDO - There is no active transaction
i also found some people suggest adding these to the database file:
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
which also hasent done anything.
now if i just remove the code inside the catch() then the error goes away and i both my update queries work.
the only difference i could spot is that all examples dont have their database connection as a function.
so where i do:
$this->connect()->beginTransaction();
they do:
$pdo->beginTransaction();
and obviously same for commit() and rollBack(). though i cant imagine this being the problem. especially when it works perfectly if i remove the catch() content.
this is where i got the code from: https://thisinterestsme.com/php-pdo-transaction-example/
i seem to have the same code apart from the connect() vs $pdo.
my connect function:
protected function connect(){
try{
$dsn = 'mysql:host=' . $this->DB_HOST . ';dbname=' . $this->DB_NAME;
$pdo = new PDO($dsn, $this->DB_USER, $this->DB_PASS);
//setting default fetch mode
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//setting errors for exceptions for try/catch
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
return $pdo;
}
catch(PDOException $error){
echo 'Connection error: ' . $error->getMessage();
}
finally{
//$pdo = null;
}
}
i fixed it with the help of the comment, and a final note at the end if someone sees this later:
this line i mentioned: $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
made it so my CRUD didnt work anymore. the other 2 setAttribute() didnt cause errors with anything at this moment.
When you call connect(), you get a different PDO object each time. Thus,
$this->connect()->beginTransaction(); // pdo object 1
$this->connect()->commit(); // pdo object 4
PDO object 4 has no transaction in progress! the Exception is normal.
Quick fix :
in you try block
$pdo = $this->connect();
$pdo->beginTransaction();
.... // replace all $this->connect() by $pdo
$pdo->commit();

Error in if/else statement MySQL [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I need some help making an if/else statement work in mysql
The if statement works proper, but the else statement buggs. I browers tells me
"Parse error: syntax error, unexpected 'else' (T_ELSE) in /var/www/domane/public_html/app/save.php on line 48" - which is the else line
It's supposed to get the current value of the row, and then add it to the new value and update it
<?php
$dsn = "databasename";
$username="username";
$password="password";
try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
//------------------------ Does the category already exist in dietTbl? -------------------------
$sql="SELECT COUNT(*) AS subjectcount FROM dietTbl WHERE day=CURDATE()";
try {
$st = $conn->prepare($sql);
$st->bindValue(":mainsubject",$mainSubject, PDO::PARAM_STR);
$st->execute();
$row=$st->fetch();
$subjectcount=$row["subjectcount"]; // if >0 the yes, the category already exists
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
};
//------------------------ If it dosn't, insert it into dietTbl -------------------------
if ($subjectcount==0) {
$sql="INSERT INTO dietTbl (day, vegetables, fullgrain, milk, water) values (:day, :vegetables, :fullgrain, :milk, :water)";
try {
$st = $conn->prepare($sql);
$st->bindValue(":day",$_POST["day"], PDO::PARAM_STR);
$st->bindValue(":vegetables",$_POST["vegetables"], PDO::PARAM_STR);
$st->bindValue(":fullgrain",$_POST["fullgrain"], PDO::PARAM_STR);
$st->bindValue(":milk",$_POST["milk"], PDO::PARAM_STR);
$st->bindValue(":water",$_POST["water"], PDO::PARAM_STR);
$st->execute();
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}
};
//------------------------ If it already exists, update dietTbl -------------------------
else {
SELECT SUM(vegetables) AS totalvegetables, SUM(fullgrain) AS totalfullgrain, SUM(milk) AS totalmilk, SUM(water) AS totalwater FROM dietTbl
$sql="UPDATE INTO dietTbl (vegetables, fullgrain, milk, water) values (:vegetables+totalvegetables, :fullgrain+totalfullgrain, :milk+totalmilk, :water+totalwater)";
try {
$st = $conn->prepare($sql);
$st->bindValue(":vegetables",$_POST["vegetables"], PDO::PARAM_STR);
$st->bindValue(":fullgrain",$_POST["fullgrain"], PDO::PARAM_STR);
$st->bindValue(":milk",$_POST["milk"], PDO::PARAM_STR);
$st->bindValue(":water",$_POST["water"], PDO::PARAM_STR);
$st->execute();
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}
};
echo "Information saved";
$conn=null; //Close database connection
?>
From this part of code:
};
//------------------------ If it already exists, update dietTbl ----------
else {
remove ";"

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

I can not insert into MariaDB table with my PHP script [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I recently moved to MariaDB, because since MySQL 5.6 it has been failing a lot for me.
MariaDB works flawlessly but, in a new project, I cannot insert data to the database with a PHP script. I can only insert manually. I have made no changes from scripts working with MySQL.
The INSERT statement is:
INSERT INTO participantes (nome, curso, email, equipe) VALUES (:nome, :curso, :email, :equipe);
And the script which should be inserting is:
$stmt = $this->dbh->prepare($this->SQL_INSERT);
$nome = $participante->nome();
$curso = $participante->curso();
$email = $participante->email();
$equipe = $participante->equipe();
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':curso', $curso);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':equipe', $equipe);
$stmt->execute();
The "participante" functions return data to be used, with no problems. Everything is inside a try/catch block, which reports no exceptions.
My PDO class is as follows:
class Connection extends PDO {
private $dsn = 'mysql:host=localhost;port=3307;dbname=dacu';
private $usr = 'dacu';
private $pwd = 'my password';
public $handle = null;
function __construct() {
try {
if ($this->handle == null) {
$dbh = new PDO($this->dsn, $this->usr, $this->pwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->handle = $dbh;
return $this->handle;
}
}
catch (PDOException $e) {
throw new Exception('Não foi possível conectar-se ao banco de dados: ' . $e->getMessage());
}
catch (Exception $e) {
throw new Exception('Um erro não identificado ocorreu: ' . $e->getMessage());
}
}
}
And using controller->insert gives me:
Warning: PDO::prepare(): SQLSTATE[00000]: No error: PDO constructor was not called in C:\Webserver\Files\dacu\controller\EquipesController.php on line 25
I can post code on pastebin if necessary, just ask.
Check your connection, then try this way, its working fine:
//first you need a connection to mysql use this and replace the variables
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db_name.'', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//then do the insert variable
$sql = 'INSERT INTO encomendas (`nome`, `user`, `id`, `email`) ';
$sql .= 'VALUES (:nome, :curso, :email, :equipe )';
$query = $dbh->prepare($sql);
//bindParam with your own variables
$query->bindParam(':nome', $varDoNome, PDO::PARAM_STR);
$query->bindParam(':curso', $varDoCurso, PDO::PARAM_STR);
$query->bindParam(':email', $varDoEmail, PDO::PARAM_STR);
$query->bindParam(':equipe', $varDaequipe, PDO::PARAM_STR);
//execute query
$query->execute()
;

Categories