【发布时间】:2013-04-06 06:00:29
【问题描述】:
我之前编写了这个代码,但它不起作用。
我意识到我可以更简单地做到这一点,但我正在尝试使用 OOP。
所以这里是代码..
database.class.php
<?php
class config {
public $host;
public $user;
public $pass;
function __construct($host=NULL,$user=NULL,$pass=NULL) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
}
function __destruct() {}
}
class database {
private $host;
private $user;
private $pass;
private $config;
function __construct($config) {
$this->config = $config;
}
function __destruct() {}
public function openCon() {
mysql_connect($this->host,$this->user,$this->pass);
if (mysql_errno()) {
printf('Failed to connect: %s', mysql_error());
} else {
echo 'Connected to DB successfully.<br/><br/>';
}
}
public function closeCon() {
try {
mysql_close();
echo 'Successfully closed connection.<br/><br/>';
} catch (exception $e) {
echo $e;
}
}
}
?>
index.php
<?php
include('db.class.php');
$con = new config('localhost','root','');
$etc = new database($con);
$etc->openCon();
mysql_select_db('tester') or die(mysql_error());
$query1 = mysql_query('SELECT * FROM person') or die(mysql_error());
$rows = mysql_fetch_array($query1) or die(mysql_error());
echo 'First: ' . $rows['First'];
echo 'Age:' . $rows['Age'];
$etc->closeCon();
?>
我确定这其中存在明显的错误。谁能帮我找到并修复它们?
它说:用户''@'localhost'拒绝访问数据库'tester'
不知道为什么。
我将 root 指定为用户,但它返回 '' 作为我请求使用的用户。
它得到了正确的主机和数据库。
我的本地 root 用户没有密码,所以...
有什么想法吗?
【问题讨论】:
-
Access denied错误表示您没有提供正确的登录信息。先解决这个问题。 -
@SverriM.Olsen 就是这样。这是正确的。我以前用这些详细信息登录过。