尝试使用 PHP OOP apporoach 从 MySQLi 获取数据,当我确定数据库中有匹配行时,我得到了No rows
我有一个名为db
的类,它以db.inc.php
的形式存储在文件中,就像
<?PHP
class db {
private $DBSERVER;
private $DBUSERNAME;
private $DBPASSWORD;
private $DBNAME;
protected function connect(){
$this->DBSERVER = "localhost";
$this->DBUSERNAME = "root";
$this->DBPASSWORD = "";
$this->DBNAME = "maator";
$conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
?>
我有一个名为SetData
的扩展类SetData.inc.php
它喜欢
<?PHP
include_once('db.inc.php');
class SetData extends db {
private $page;
private $region;
private $conn;
function __construct() {
$this->conn = new db();
}
public function SetBox($vpage, $vregion){
$this->page = $vpage;
$this->region = $vregion;
$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
$stmt->bind_param("ss", $this->page, $this->region);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows === 0) exit('No rows');
$stmt->bind_result($titlerow,$descriptionrow);
$stmt->fetch();
$title = $titlerow;
$description = $descriptionrow;
$stmt->free_result();
$stmt->close();
}
}
?>
最后在头版我有
<?PHP
$page = 'game';
$region = 'ASIA';
include '../inc/SetData.inc.php';
$cls = new SetData();
$cls->SetBox($page, $region);
我不知道
dbconnect()
是什么,你需要在这里调用你的connect()
方法:
//$this->conn = new dbconnect(); // NO!
$this->conn = $this->connect();
另外,您不应该在此处调用connect()
,您已经在$conn
中建立了连接:
//$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?"); // NO!
$stmt = $this->conn->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
那么,你想用$title
和description
做什么? 也许归还它们?
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
return array('title' => $titlerow, 'description' => $descriptionrow);
然后调用SetBox()
并显示:
$result = $cls->SetBox($page, $region);
echo $result['title'];
或设置属性:
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$this->title = $titlerow;
$this->description = $descriptionrow;
$stmt->free_result();
$stmt->close();
然后调用SetBox()
并显示:
$cls->SetBox($page, $region);
echo $cls->title;