0

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

2
  • In the same way you get the connection... you need to wrap in a Try/Catch... Commented Aug 5, 2015 at 14:22
  • $stmt->bindParam(':date', $date, PDO::PARAM_INT); .... you havent defined a :date in the sql query... so why are you bidning it? Commented Aug 5, 2015 at 14:42

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.