gpt4 book ai didi

php - 使用 PHP OO 类获取行

转载 作者:行者123 更新时间:2023-11-29 03:39:24 26 4
gpt4 key购买 nike

我创建了一个类函数,它将从我的数据库中的表中获取行以及一个可选参数。这在获取单行时有效,但是当返回多行时我无法使它工作。

这是用户类中的内容

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,请耐心等待)

最佳答案

我还在学习 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;
}

修改最后一部分以满足您的需要。

关于php - 使用 PHP OO 类获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com