我创建了一个项目类 (item.class.php) 和 itemDAO 类 (itemDAO.class.php),我还有另一个 php 文件 (test.php)。我想使用 test.php 类中的那些类将数据插入数据库。我还有一个数据库类(db.class.php)。在这里,我坚持将对象的(项目)值传递给 itemDAO 类中的函数。
这是我的 item.class.php
<?php
class item {
private $id;
private $name;
private $description;
public function item($_id,$_name,$_description){
$this->id=$_id;
$this->name=$_name;
$this->description=$_description;
}
public function setId( $id )
{
$this->id = $id;
}
public function setName( $name )
{
$this->name = $name;
}
public function setDescription( $description )
{
$this->description = $description;
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function getDescription()
{
return $this->description;
}
}
?>
这是我的 itemDAO.class.php
<?php
include("db.class.php");
include("item.class.php");
class itemDAO {
public function __construct() {
$d=new db();
}
public function AddItem(&$item) { //I am stuck here
$result = $db->query("INSERT INTO item VALUES('$i->') ");//Im stuck here
}
}
?>
如何获取项目类对象以从对象中获取值并传递给 sql 查询。我不擅长 php 并且很了解 java。在java中我们可以这样调用
public boolean addItem(Item I) {
String query = "insert into Item(Item_Id, Item_Name, Item_Category, Measuring_Unit, Last_Price_Rate) values ('" + I.getItemID() + "','" + I.getItemName() + "','" + I.getItemCategory() + "','" + I.getMeasuringUnit() + "','" + I.getLastPriceRate() + "')";
System.out.println(query);
}
这是我的 test.php
<?php
include("item.class.php");
include("db.class.php");
include("itemDAO.class.php");
$id="3";
$name="aaa";
$descriptio="hi";
$item= new item($id,$name,$descriptio);
$dao=new itemDAO();
$dao->AddItem($item->getId(),$item->getName(),$item->getDescription());
?>
我的数据库类
<?php
class db {
private $link;
// private $host="localhost", $username="root", $password="123", $database="item";
public function __construct(){
$this->host = "localhost";
$this->username = "root";
$this->password = "123";
$this->database = "item";
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
?>
如何使用面向对象的 PHP 做同样的事情?