MySQLi 准备语句和 OOP PHP 查询 Returns 0 行

MySQLi Prepare Statement and OOP PHP Query Returns 0 Row

尝试使用 PHP OOP 方法从 MySQLi 获取数据 我得到 No rows 虽然我确定我在数据库中有匹配行

我有一个名为 db 的 class 作为 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.inc.php 中有一个名为 SetData 的扩展 class,它喜欢

<?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` = ?");

那么,你想用$titledescription做什么?也许 return 他们?

    $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;