drplww2505 2014-08-02 19:50
浏览 46
已采纳

在PHP中使用OOP查询数据库

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?

<?php
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
    $sql->execute();
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了