pdoexception not outputting error - php

$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'username', 'password');
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $_POST['username'], ':password' => $_POST['password1'], ':email' => $_POST['email'], ':county' => $_POST['county']));
echo 'Success';
}
catch (PDOException $e)
{
echo $e->getMessage();
}
Hi, I am not completely familiar with pdo but I thought I would add a few error exceptions, except I won't actually display the error normally as I don't want everyone to know my schema. In this case I changed my working code to a non working code by changing "...,county)" to "....,count)" which obviously did not insert into the database at all but still shown "Success" and no error.
Please help :(

You need to set PDO error mode to throw exception.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Related

My form won't send informations to my database [PHP] [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed last year.
I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
If the query fails, or let's say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
By default PDO is not in a state that will display errors. you need to provide the following in your DB connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
More info can be seen Here
1.Add ERRMODE_EXCEPTION mode after your db connection:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
2.And than you must use try{} catch{} method for all your mysql query. Like this:
try {
$SQL = "DELETE FROM items WHERE item_id=:item_id";
$m = $dbh->prepare($SQL);
$m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$m->execute();
//success
$return = "Your success message.";
}
catch (PDOException $e) {
//error
$return = "Your fail message: " . $e->getMessage();
}
You should use this:
return $exception->getMessage();
See the page on the documentation of Exception class:
http://www.php.net/manual/en/exception.getmessage.php

Issues trying to connect to a remote Microsoft SQL Server with PHP using PDO

I am trying to make a simple web application using just HTML5, CSS, Javascript, and PHP. The purpose of the app is to pull data off of a remote Microsoft SQL Server Database and put the data in a schedule table based primarily off of date. I have most of my frameworking up, I am just having a lot of trouble trying to pull the data off of the database. I've tried many different driver setup and I can't seem to hit anything except a brick wall.
some of the setups I've tried are :
<code>
try {
$conn = new PDO("sqlsrv:server=$hostname; database=$dbname", $username, $pw);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo"Connected Successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
</code>
and
<code>
$dsn = "sqlserver:host=$hostname;dbname=$dbname;port=$port;charset=utf8");
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $pw, $opt);
</code>
I am not the most versed in PHP, and I'm trying to get better. But, I've been beating my head against a wall with this one issue for almost a week now. Any help would be greatly appreciated.
Thank you very much in advance.
EDIT: for anyone who comes later to try to find an answer to a question like this, I'm not sure what I did. I never ended up editing php.ini the setup that did work was
try {
$conn = new PDO("sqlsrv:Server=<IP ADDRESS>,<PORT>;Database=<DBNAME>", $username, $pw);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo"Connected Successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if you are still having trouble you can use this to print out all the drivers that are installed:
foreach(PDO::getAvailableDrivers()as $driver){
if($driver==NULL){
echo"No PDO Drivers were found";
}else{
echo $driver . "<br />";

PHP PDO - There is no active transaction

I am having problem with transactions in php script. I would like to make multiply queries and be able to recall them all, if at least one of them fails. Below you can find a simple example of the script I am using:
$tags_input = array(6,4,5);
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',
DB_USER, DB_PASSW, array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$conn->beginTransaction();
$sql = "INSERT INTO projects (id, pr_id, enabled) VALUES ( :val0, :val1, :val2)";
$stmt = $conn->prepare($sql);
if(count($tags_input)>0){
for($i = 0;$i<count($tags_input);$i++){
$stmt->bindValue(':val0', 57);
$stmt->bindValue(':val1', $tags_input[$i]);
$stmt->bindValue(':val2', 'Y');
$result = $stmt->execute();
}
}
$res1 = $conn->commit();
$conn->rollBack();
Now, this example generates an error:
Uncaught exception 'PDOException' with message 'There is no active
transaction'
If I erase the line $conn->rollBack();, the error disappears. Therefore I cannot understand, why pdo object can't see open transaction (begintransaction and commit do not generate any errors). I also tried putting rollBack() inside the transaction, but made no difference. I was still getting an error 'There is no active transaction'.
I am running PHP 5.6 and Mysql tables on InnoDB.
Wrap your transaction code inside a try-catch statement.
//try {
$tags_input = array(6,4,5);
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',
DB_USER, DB_PASSW, array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$conn->beginTransaction();
$sql = "INSERT INTO projects (id, pr_id, enabled) VALUES ( :val0, :val1, :val2)";
$stmt = $conn->prepare($sql);
if(count($tags_input)>0){
for($i = 0;$i<count($tags_input);$i++){
$stmt->bindValue(':val0', 57);
$stmt->bindValue(':val1', $tags_input[$i]);
$stmt->bindValue(':val2', 'Y');
$result = $stmt->execute();
}
}
$res1 = $conn->commit();
} catch (Exception $e) {
$conn->rollBack();
echo "Failed: " . $e->getMessage();
}
EDIT
A really well-based and straight-forward explanation of the answer was provided by Richard as a comment.
The reason you got error is because you were trying to close a transaction when it was already closed. beginTransaction opens one, and EITHER rollBack OR commit closes it. You have to avoid doing BOTH actions, meaning commit/rollback, for a single beginTransaction statement, or you'll get an error. The above try/catch code ensures that only one closing statement is executed.
Peter and Richards answers are already correct, but there is one little mistake in the code from the transaction structure (and i can't add a comment).
The $connection->beginTransaction() must be outside of the try-catch block. When you're start the beginTransaction() in the try-block and your Database Operations throws an exception, the catch-block doesn't know something from an active transaction. So, you get the same error:
"There is no active transaction".
So the structure should be as well:
Get the Connection.
Start the Transaction with $connection->beginTransaction()
Open the try-catch block.
The try-block contains the $connection->commit() after DB Operations.
The catch-block contains the $connection->rollback() before a throw Exception.
So your code should look like this:
$tags_input = array(6,4,5);
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',
DB_USER, DB_PASSW, array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
//Begin Transaction
$conn->beginTransaction();
try {
$sql = "INSERT INTO projects (id, pr_id, enabled) VALUES ( :val0, :val1, :val2)";
$stmt = $conn->prepare($sql);
if(count($tags_input)>0){
for($i = 0;$i<count($tags_input);$i++){
$stmt->bindValue(':val0', 57);
$stmt->bindValue(':val1', $tags_input[$i]);
$stmt->bindValue(':val2', 'Y');
$result = $stmt->execute();
}
}
$res1 = $conn->commit();
} catch (Exception $e) {
$conn->rollBack();
echo "Failed: " . $e->getMessage();
}

pdo catch and output mysql errors [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed last year.
I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
If the query fails, or let's say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
By default PDO is not in a state that will display errors. you need to provide the following in your DB connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
More info can be seen Here
1.Add ERRMODE_EXCEPTION mode after your db connection:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
2.And than you must use try{} catch{} method for all your mysql query. Like this:
try {
$SQL = "DELETE FROM items WHERE item_id=:item_id";
$m = $dbh->prepare($SQL);
$m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$m->execute();
//success
$return = "Your success message.";
}
catch (PDOException $e) {
//error
$return = "Your fail message: " . $e->getMessage();
}
You should use this:
return $exception->getMessage();
See the page on the documentation of Exception class:
http://www.php.net/manual/en/exception.getmessage.php

PHP PDO Doesn't insert new records

I do not understand what my problem seem to be.
I got the following PHP code:
include_once 'db.inc.php';
try
{
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
}
catch(PDOException $e)
{
echo 'Connection failed: ', $e->getMessage();
exit();
}
$title = htmlentities($_POST['title']);
$entry = htmlentities($_POST['entry']);
$sql = "INSERT INTO entries (title, entry) VALUES (?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($title, $entry));
$stmt->closeCursor();
I do not receive any error of any kind and the script seem to have worked however it does not insert anything into the database.
No matter what I try it doesn't do anything.
edit
Sorted :)
I didn't know about $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);.
It gave me "Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'".
Turns out I wrote mysql:host=127.0.0.1;db_name=test1 instead of mysql:host=127.0.0.1;dbname=test1 in my config file.
Thank you very much for help!
Set PDO to throw exceptions when execution fails
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories