I’m trying to retrieve data from my table using PDO, only I can’t seem to output anything to my browser, I just get a plain white page.
try { // Connect and create the PDO object $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 $lastIndex = 2; $sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20" $sth = $conn->prepare($sql); $sth->execute(array(':lastIndex' => $lastIndex)); $c = 1; while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { echo 'ALL STYLING ETC RESULTS HERE'; $c++; } $conn = null; // Disconnect }
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
EXAMPLE.
This is your dbc class
<?php class dbc { public $dbserver = 'server'; public $dbusername = 'user'; public $dbpassword = 'pass'; public $dbname = 'db'; function openDb() { try { $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . ''); } catch (PDOException $e) { die("error, please try again"); } return $db; } function getAllData($qty) { //prepared query to prevent SQL injections $query = "select * from TABLE where qty = ?"; $stmt = $this->openDb()->prepare($query); $stmt->bindValue(1, $qty, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); return $rows; } ?>
your PHP page:
<?php require "dbc.php"; $getList = $db->getAllData(25); foreach ($getList as $key=> $row) { echo $row['columnName'] .' key: '. $key; }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0