Reputation: 117
I am having a look at connecting to a MySQL database for the first time using PDO. I have a working script to SELECT and display a timestamp and although I can get it to display a connection error I can't see how to display an error (say for eg) trying to access a non-existent table
My connection routine is in a separate file connectpdo.php:
try {
$pdo = new PDO($dsn, $mysql_username, $mysql_password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}//end try
catch (PDOException $error) {echo 'Connection failed: ' . $error- >getMessage();}
Here is the main script:
include("connectpdo.php");
$sql= "SELECT date FROM phpmysqlautobackup_log ORDER BY date DESC LIMIT 1 ";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':date', $date, PDO::PARAM_INT);
$stmt->execute();
$obj = $stmt->fetchObject();
$pdo = null;
$date=$obj->date;
echo"<p style='color: black; font-weight: 600; text-align: center; margin: 0px; padding-top: 25px;'>LAST DB BACKUP</p>";
$date1 = date("l", $date);
$date2 = date("j M Y", $date);
$date3 = date("H:i", $date);
echo "<p style='color: black; text-align: center; margin: 0px;'>".$date1."<br>".$date2."<br>".$date3."</p>";
Could any kind person please give me a pointer
Thanx
Bob
Upvotes: 0
Views: 45
Reputation: 8616
In the same way you get the connection... you need to wrap in a Try/Catch...
try {
$sql= "SELECT date FROM phpmysqlautobackup_log ORDER BY date DESC LIMIT 1 ";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':date', $date, PDO::PARAM_INT);
$stmt->execute();
$obj = $stmt->fetchObject();
$pdo = null;
$date=$obj->date;
echo"<p style='color: black; font-weight: 600; text-align: center; margin: 0px; padding-top: 25px;'>LAST DB BACKUP</p>";
} catch(PDOException $error) {
echo 'Queryfailed: ' . $error- >getMessage();
}
Also, there is no need to do $pdo = null; The PDO object will cease to be when script ends (unless initialised as persistent).
Upvotes: 3