[英]Need some help debugging this PHP
我之前对此进行了编码,但无法正常工作。
我意识到我可以做得更简单,但是我正在尝试使用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用户没有密码,所以...
有任何想法吗?
好的,问题是主机,用户和密码从未设置过。 在database
构造函数中查找。 您仅设置配置。
要么以某种方式设置私有database
属性,要么在openCon()
使用配置对象。
或者,甚至更好,只需废弃config
对象。 目前,它没有任何重要作用。 只需像下面那样更改database
构造函数并完成它:
function __construct($host, $user, $pass) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
}
最后,如果__destruct()
方法不执行任何操作,则不需要包含它。
您的每件事都是正确的,只是您需要更改数据库类。 您将$ config作为对象传递给数据库类的构造函数,因此只需很少更改即可从该对象访问变量。 它应该是
class database {
private $host;
private $user;
private $pass;
private $config;
public $Connectionlink;
function __construct($config) {
$this->host = $config->host;
$this->user = $config->user;
$this->pass = $config->pass;
}
// function __destruct() {} as your destruct function doing noting so you need not to include this.
public function openCon() {
$this->Connectionlink= 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;
}
}
}
mysql_select_db需要两个参数,因此应该
mysql_select_db('tester', $etc->Connectionlink) or die(mysql_error());
只需尝试在xampp中使用cmd导航到您的mysql目录,其“ C:\\ xampp \\ mysql \\ bin”
然后键入“ mysql -u root”,并检查您是否正在访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.