<?php $host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password'; $conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?> <?php $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); ?> <?php do { // print your results here ex: next line echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>'; } while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?>
Happy coding!
Remember to shut down and free resources
<?php $query->closeCursor(); ?>
EDIT
I recommend not repeating the error messages as soon as you confirm your code functions as expected; however, if you just want to use plain text, you can do it ...
You can add this to your connection block ...
if ($conn->connect_error) { die("Database Connection Failed"); exit; }
You can also change your query block ...
try { $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); } catch (PDOException $e) { die("Could not get the data you requested"); exit; }
Again, it is recommended that errors not be repeated. Use the error check function for debugging only .
source share