sql >> Base de Datos >  >> RDS >> Mysql

Obtenga resultados de MySQL usando PDO

EJEMPLO. Esta es tu clase 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;
    }    
?>

su página PHP:

<?php 
require "dbc.php";

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

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