我创建了一个类函数,它将从数据库中的表中获取行以及可选参数。获取单行时这是有效的,但是当返回多行时,我无法使其工作。
以下是Users类
中的内容public function getUsers($filter="") {
$Database = new Database();
if($filter == 'male')
$extra = "WHERE gender = 'm'";
$sql = "SELECT *
FROM users
$extra";
if ($Database->query($sql))
return $Database->result->fetch_assoc();
else
return false;
}
数据库类
class Database {
private $db = array();
private $connection;
private $result;
public function __construct() {
$this->connect();
}
public function connect() {
$this->connection = mysqli_connect('mysql.com', 'username', 'pass');
mysqli_select_db($this->connection, 'database');
}
public function query($sql) {
$this->result = mysqli_query($this->connection, $sql);
return $this->result;
}
这是用于尝试和显示行的代码
if ($student = $User->getUsers($filter)) {
echo "<table>\n";
echo "<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td><td></td><td></td></tr>";
foreach($student as $row) {
echo "<tr>";
echo "<td>$row[col1]</td>";
echo "<td>$row[col2]</td>";
echo "<td>$row[col3]</td>";
echo "<td>$row[col4]</td>";
echo "<td>$row[col5]</td>";
echo "<td>$row[col6]</td>";
echo "</tr>\n";
}
echo "</table>";
}
(我正在学习OO PHP,请耐心等待)
答案 0 :(得分:0)
您的代码中不清楚$result
来自哪个......
您应该调用由以下函数返回的对象的fetch_assoc()方法:
$mysqli->query($query)
答案 1 :(得分:0)
为什么两次使用$result->fetch_assoc()
?你正在返回一个数组..你应该处理$student
。
答案 2 :(得分:0)
我还在学习OOP,但我用过这个:
protected $connection, $result, $_numRows;
public function query($sql)
{
$this->result = mysql_query($sql, $this->connection);
$this->_numRows = mysql_num_rows($this->result);
}
/*
* @desc get result af query
*
* @returns string $result
*/
public function getResult()
{
return $this->result;
}
/*
* @desc Return rows in table
* @returns int $_numRows
*/
public function numRows()
{
return $this->_numRows;
}
/*
* @desc Count rows and add to array
* @return string $rows array
*/
public function rows()
{
$rows =array();
for ($x=0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->result);
}
return $rows;
}
然后你可以用这样的东西来获取行:
public function getUsers($filter="") {
$Database = new Database();
if($filter == 'male')
$extra = "WHERE gender = 'm'";
$sql = "SELECT *
FROM users
$extra";
if ($this->numRows() == 0) {
echo "No rows found";
} else {
foreach ($this->rows() as $b) {
$c = array('something' => $b['col']);
}
return $c;
}
修改最后一部分以满足您的需求。