2014-08-02 19:50
浏览 45


I am new to OOP in PHP and i am trying to create a class, and then query the database. ATM the code looks like this and i am stuck in the query part. The query is ok, but it should use the class created. Can anyone help me please?

class Products {

  //objekto kintamieji
  public $category_id;  
  public $product_id;

  public function __construct($category_id, $product_id){
    $this->category_id = $category_id;
    $this->product_id = $product_id;

  public function query_the_database() {   
    if($xml->action == 'getProducts') {
      $query = mysql_query("SELECT * FROM product WHERE category_id = 1 ORDER BY product_id");
      while($row = mysql_fetch_object($query)){
        $row->pvm = $row->price - round($row->price*100/121, 2);
        $prod[] = $row;
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douchen9569 2014-08-02 20:11

    You really should be using MySQLi or, even better, PDO on your class.

    And, I highly recommend that you establish your connection in a separate class. So you have two pages: db.class.php and products.class.php.

    Well, basic tutorial:

    Establishing a connection:

    $db=new PDO("mysql:host=HOST_NAME;port=PORT;dbname=DB_NAME");

    Executing normal queries:

    $db->execute("select * from table");

    Executing queries with parameters (prepared statements):

    $sql=$db->prepare("select * from table where param1=:p1 and param2=:p2");
    $sql->bindParam(":p1", $p1); //bindParam only accepts variables
    $sql->bindValue(":p2", "Value"); //bindValue only accepts raw values

    Fetching values of prepared statements:

    $array=$sql->fetchAll(); //that will be an array containing values in column names that are in row numbers. Like this: Array([0]=>Array([0]=>"value1" [column1]=>"value1") [1]=>Array([0]=>"value2" [column1]=>"value2"))

    But please, go read about it since it will help you A LOT.

    解决 无用
    打赏 举报

相关推荐 更多相似问题