Get results from from MySQL using PDO

前端 未结 1 852
别那么骄傲
别那么骄傲 2020-12-06 23:30

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          


        
相关标签:
1条回答
  • 2020-12-06 23:52

    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;
        }
    
    0 讨论(0)
提交回复
热议问题