I have the following scenario:
In my .db.inc.php file I'm connecting to a database:
try {
$dbh = new PDO('mysql:host=' . HOST . ';dbname=' . DATABASE , USER_DB, PASSWORD_DB);
}
catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
Then I run some functions before I need the connection, but I know that the connection is established as I don't have an error thrown.
Now I need to update my database:
include('.db.inc.php');
try {
/...
$sql = "UPDATE de_request_products SET report_id = :report_id WHERE request_id = :request_id";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':report_id', $report_number, PDO::PARAM_STR);
$stmt->bindValue(':request_id', $report_request_number, PDO::PARAM_STR);
$stmt->execute();
}
catch (PDOException $e){
die('Error!: ' . $e->getMessage() . '<br/>');
}
If above written try block fails, I want to have a try catch block in the Exception Handler to update the database:
// ....
catch (PDOException $e){
try {
//SEND EMAIL AND
$sql = "INSERT INTO de_failed_requests (datum, reason) VALUES (:datum, :reason)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':datum', $date, PDO::PARAM_STR);
$stmt->bindValue(':reason', $e->getMessage(), PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $f) {
die('NOTHING WORKS AT ALL!'. $f->getMessage());
}
die('Error!: ' . $e->getMessage() . '<br/>');
}
Would this be the way to go or is there a more efficient way?
Related
I use php with PDO to manage a database with mysql. When I run the server I can read and insert data in the tables of my database, everything is correct. But, the next day I use my script, my code return a empty Array when I read and don't insert any data. Furthermore, my script don't throw any exception when does that, and I don't understand why.
I run my database connection with this code:
try {
$this->dataBase = new PDO('mysql:dbname=' . $this->dbName . ';host=' .
$this->host . ';port=' . $this->port,
$this->user, $this->pass);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
I get the data from my database with the code:
try {
$sql = $this->dataBase->prepare("SELECT username FROM teachers");
$sql->execute();
$result = $sql->fetchAll();
return $result;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$this->reconnect();
}
I do something wrong?
I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);
The problem I am having is on occasion (1 of every 8 or so) insertions to the database, the string value of (fileLocation) will be incomplete. so for example..
what should be "filecomplete.mp4" will be inserted as "filecomple".
Has anyone experienced this before or have any ideas as to what the problem could be?
Here is my insert statement.
public function addNewGame($gameID, $receiverID, $senderID, $gameTrack, $fileLocation){
$this->gameid = $gameID;
$this->receiverid = $receiverID;
$this->senderid = $senderID;
$this->gameTrack = $gameTrack;
$this->filelocation = $fileLocation;
$SQUERY = "SELECT GameId FROM ActiveGames WHERE GameId = :gameid";
try{
$stamt = $this->connection->prepare($SQUERY);
if ($stamt === false) {
throw new Exception($this->connection->error);
}
$stamt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stamt->execute();
$result = $stamt->fetchAll();
$resultCount = count($result);
if($resultCount > 0){
echo "existing record";
} else{
$QUERY = "INSERT INTO ActiveGames (GameId,
ReceiverId,
SenderId,
GameTrack,
FileLocation)
VALUES (
:gameid,
:receiverid,
:senderid,
:gametrack,
:filelocation)";
try{
$stmt = $this->connection->prepare($QUERY);
if ($stmt === false) {
throw new Exception($this->connection->error);
}
$stmt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stmt->bindValue(':receiverid', $this->receiverid, PDO::PARAM_INT);
$stmt->bindValue(':senderid', $this->senderid, PDO::PARAM_INT);
$stmt->bindValue(':gametrack', $this->gameTrack, PDO::PARAM_STR);
$stmt->bindValue(':filelocation', $this->filelocation, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
}
catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
<?php
$sql = utf8_decode("SELECT Photo,Code_Musicien FROM Musicien WHERE Code_Musicien=?");
try {
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['image']));
$stmt->bindColumn(1, $lob, PDO::PARAM_LOB);
} catch (PDOException $e) {
echo "Data could not be retrieved from the database." . $e->getMessage();
}
$stmt->fetch(PDO::FETCH_BOUND);
if (is_string($lob)) {
$lob = fopen('data://image/jpeg;base64,' . base64_encode($lob), 'r');
}
fpassthru($lob);
?>
I'm just trying to do a simple insert:
$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN, WEBSITE_PW);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
echo 'PDO SUCCESS';
}else{
echo 'PDO FAILURE';
}
But it's failing. Can someone tell me why? And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?
But it's failing. Can someone tell me why?
Hard to say. Should those values be quoted? The error thrown by MySQL would be useful to diagnose the problem. Which leads me to...
And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?
So long as PDO is set up to throw exceptions on errors...
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
...wrap it in a try/catch block and examine the exception thrown.
try {
$query->execute(...);
} catch (PDOException $e) {
echo $e->getMessage();
}
By default, PDO's error mode is ERRMODE_SILENT so it won't complain if anything goes wrong. To see real errors, either set it to ERRMODE_WARNING or ERRMODE_EXCEPTION to throw exceptions. http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
try {
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
$query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))
}
catch (PDOException $e) {
echo "Query failed: " $e->getMessage();
}
With something like this you will be able to get the error.
$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN, WEBSITE_PW);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
try {
if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
echo 'PDO SUCCESS';
}else{
echo 'PDO FAILURE';
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}