简体   繁体   English

在PHP中使用OOP查询数据库

[英]Query the database with OOP in PHP

I am new to OOP in PHP and i am trying to create a class, and then query the database. 我不熟悉PHP中的OOP,而是试图创建一个类,然后查询数据库。 ATM the code looks like this and i am stuck in the query part. ATM的代码看起来像这样,我陷入了查询部分。 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;
      }
    }
  }
}

You really should be using MySQLi or, even better, PDO on your class. 您确实应该在课堂上使用MySQLi甚至更好的PDO

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 . 因此,您有两个页面: db.class.phpproducts.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. 但是,请继续阅读,因为它将对您有很大帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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