【发布时间】:2014-09-06 14:27:05
【问题描述】:
当我在没有类的情况下使用 mysqli 时,一切正常:
index.php
require_once(dirname(__FILE__) . '/config.php');
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$queryText = "SELECT * FROM User";
if($query = $mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $mysqli->errno . " " . $this->mysqli->error;
}
?>
但是当我开始在类中使用 mysqli 时,出现了问题。 connectDB 没有给出任何错误,所以我连接到 DB。但是当尝试做任何查询时,它给了我“没有选择数据库错误” index.php 的结果是:Error 1046 No database selected
index.php
<?php
require_once(dirname(__FILE__) . '/banana.php');
$banana = new Banana(1);
if ($banana->connectDB()) {
$banana->doQuery();
}
?>
banana.php
<?php
require_once(dirname(__FILE__) . '/config.php');
class Banana {
private $mysqli, $userId, $query;
function __construct($userId) {
$this->userId = $userId;
}
function __destruct() {
$this->mysqli->close();
}
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
if ($this->mysqli->connect_errno) {
echo "Error (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
return false;
}
return true;
}
public function doQuery() {
$queryText = "SELECT * FROM User";
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $this->mysqli->errno . " " . $this->mysqli->error;
}
}
?>
所以这很令人沮丧。我在 php 中大约 2 周,但几天都找不到答案。我想答案很明显,但我看不到。 感谢您的时间和耐心。
【问题讨论】:
-
检查你的变量:
$results = $query->fetch_array();- '$this' 在哪里? -
$mysqli 是 Banana 类的私有属性。我在课堂上的任何地方都将它用作 $this->mysqli.
-
你不应该用给出的答案来改变你原来的问题,因为那样答案就没有意义了。
-
@jeroen 好的,下次不会了