【发布时间】:2010-12-19 18:21:47
【问题描述】:
我正在尝试用 PHP 构建一个简单的数据库类,并且我正在使用 MySQL。
现在我卡住了,我不知道如何从数据库中显示一行结果。我已经解决了如何从数据库中获取多行但现在我试图只显示一个,如用户名、电子邮件、级别、reg_date。
我的代码:
class Database {
public $mysql;
function __construct()
{
$this->mysql = new mysqli(host, user, password, db) or die('There was a problem connecting to the db');
}
function multiLine($sql)
{
$this->mysql->query("SET NAMES 'utf8'");
$this->mysql->query("SET CHARACTER SET 'utf8'");
if(($result = $this->mysql->query($sql)) != NULL) {
$x = array();
while($row = $result->fetch_array()) {
$x[] = $row;
}
return $x;
}
else {
echo $this->mysql->error;
}
}
function singleLine($sql)
{
$one = array();
if(($one = $this->mysql->query($sql)) != NULL)
{
$one = $result->fetch_array(); // Error here
}
return $one;
}
function __destruct() {
// close out the database connection;
$this->mysql->close();
}
}
我的函数 multiLine 工作,我像这样使用它:
$db = new Database();
$sql = 'SELECT * FROM users ORDER BY id DESC';
$response = $db->multiLine($sql);
<?php foreach($response as $r) : ?>
<p>ID: <?php echo $r['id']; ?></p>
<p>Username: <?php echo $r['username']; ?></p>
<?php endforeach; ?>
那么有人可以给我一个提示如何解决这个问题吗?或者也许有人有一个链接到一个很棒的用 PHP 制作数据库类的教程。
【问题讨论】: