使用 PDO 从 MySQL 获取结果

时间:2023-04-08
本文介绍了使用 PDO 从 MySQL 获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 PDO 从我的表中检索数据,但我似乎无法向浏览器输出任何内容,我只是得到一个纯白色页面.

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
}

推荐答案

EXAMPLE.这是你的 dbc 课

<?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;
    }    
?>

您的 PHP 页面:

<?php 
require "dbc.php";

$getList = $db->getAllData(25);

foreach ($getList as $key=> $row) {
         echo $row['columnName'] .' key: '. $key;
    }

这篇关于使用 PDO 从 MySQL 获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:PHP:使用 PDO 从 MySQL 检索图像 下一篇:PHP sqlsrv 驱动程序和 PDO 驱动程序之间的数据类型差异

相关文章