fetchAll from database using PDO

62 Views Asked by At

So I've been working on this website a long time but the problem is most of it is MYSQL, which of course isnt very secure, so now I'm trying to update all the PHP to PDO, so far I've only managed to get the connect.php working (in the first code below). My main issue is wthin the 2nd code below, on my reviews page I'm having a hard time fetching ALL the reviews from database including (cid,uid,username,date,message & rating) and then ORDER BY DESC, I have used multiple guides but they all seem to show a different way of doing it...

<?php

$host = 'localhost';
$dbuser = 'B99';
$dbpwd = 'testpass';
$dbname = 'admin';

//set DSN//
$dsn = 'mysql:host=' . $host .';dbname=' . $dbname;

//Create PDO instance//
//Attempt MySQL server connection.//
$pdo = new PDO($dsn, $dbuser, $dbpwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

and the FetchAll code here:

<?php 

include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");

$sql = $pdo->query("SELECT * FROM `reviews` ORDER BY `cid` DESC");
$stmt = $pdo->prepare($sql);
$stmt->execute(['cid']);

$reviews = $stmt->fetchAll();
foreach ($reviews as $fetch) {

?>

<div class="eachreview" style="background-color:royalblue;">
<?php echo $fetch['rating']; ?>
<?php echo $fetch['uid']; ?>
<?php echo $fetch['message']; ?>
<?php echo date("d/m/Y" ,strtotime($fetch['date'])); ?>
</div>

<?php
} 
?>

UPDATED CODE Kinda working but displaying 1/1/1970 and no other data

<?php  
include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");

$stmt = $dbh->prepare("SELECT * FROM `reviews` WHERE cid = :cid");
$stmt->execute(array(':cid' => "cid"));

$fetch = $stmt->fetchAll();
{
?>

THIS CODE BELOW WORKS! :)

<?php  
include("/var/www/vhosts/my-web.co.uk/httpdocs/PHP/connect.php");

$stmt = "SELECT * FROM `reviews`";
$result = $dbh->query($stmt);
foreach ($result as $fetch) {
?>

<?php echo $fetch['message']; ?>
0

There are 0 best solutions below