简体   繁体   中英

Basic pdo oop in php

I'm new in php oop..I'm having trouble in showing my fields value. I have here the ff classes.

public static function getAll()
{

    self::conn();

    try
    {

        $sql = "SELECT * FROM dbo.guitar";

        $q = self::$db->prepare($sql);
        $q->execute();
        $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
                "Guitar",
                array('id', 'make', 'model', 'colour', 'price'));

    }
    catch (Exception $e)
    {
        print "Error!: " . $e->getMessage();
    }

    return $results;    
}

I want it to show from diff fields. Here is my code:

$guitars = Guitar::getAll();

I can see the values when I try using the print_r

What I want is like this.

echo $row['field1'];  echo $row['field2']; 

THank you in advance.

You are fetching result as objects, so you could do like this:

$guitars = Guitar::getAll();
foreach ($guitars as $guitar) {
  echo $guitar->getId();
  echo $guitar->getMake();
  // ... and so on
}

Addtion:

You need to have the constructor to set the property, and provide public methods to access the property.

class Guitar {
  private $id;
  private $make;
  private $model;
  private $color;
  private $price;

  public function __construct($id, $make, $model, $color, $price) {
    $this->id = $id;
    $this->make = $make;
    $this->model = $model;
    $this->color = $color;
    $this->price = $price;
  }

  public function getId() {
    return $this->id;
  }

  public function getMake() {
    return $this->make;
  }
  // and so on...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM