我是php的新手。请检查以下代码。我收到以下代码没有数据库选择错误。我在oops中编写了代码。任何帮助将不胜感激。请帮忙。我在这一行中遇到错误
die("invalid".mysql_error());'
在runquery($ query)方法中。
Dbconfig.php
<?php
class Dbconfig
{
private $connection;
public function __constructor($hostname,$username,$password,$database){
$this->connection=mysql_connect($hostname,$username,$password);
if(!$this->connection){
die(mysql_error());
}else{
if(!mysql_select_db($database,$this->connection)){
die(mysql_error());
}
}
}
function runQuery($query){
$result= mysql_query($query);
if($result){
while($row= mysql_fetch_array($result)){
$resultset[]= $row;
}
if(!empty($resultset)){
return $resultset;
}
} else {
die("invalid".mysql_error());
}
}
}
?>
的config.php
<?php
require("path to dbconfig.php");
$base="http://localhost/slvbilling/";
$hostname='localhost';
$username='root';
$password='';
$database='slv';
$connect = new Dbconfig($hostname,$username,$password,$database);
?>
答案 0 :(得分:3)
尝试使用Dbconfig.php文件中的以下代码
<?php
class Dbconfig
{
private $connection;
public function __construct($hostname,$username,$password,$database){
$this->connection=mysql_connect($hostname,$username,$password);
if(!$this->connection){
die(mysql_error());
}else{
if(!mysql_select_db($database,$this->connection)){
die(mysql_error());
}
}
}
function runQuery($query){
$result= mysql_query($query);
if($result){
while($row= mysql_fetch_array($result)){
$resultset[]= $row;
}
if(!empty($resultset)){
return $resultset;
}
} else {
die("invalid".mysql_error());
}
}
}
?>
它的构造函数只能尝试上面的代码,它可能有所帮助!
答案 1 :(得分:1)
使用mysql函数放置or die(mysql_error())
而不是放置冗余条件。
请尝试使用以下代码..
<?php
class Dbconfig
{
private $connection;
public function __construct($hostname,$username,$password,$database){
$this->connection=mysql_connect($hostname,$username,$password)or die(mysql_error());
mysql_select_db($database,$this->connection))or die(mysql_error());
}
function runQuery($query){
$result= mysql_query($query)or die("invalid".mysql_error());
if($result){
while($row= mysql_fetch_array($result)){
$resultset[]= $row;
}
if(!empty($resultset)){
return $resultset;
}
}
}
}
?>
答案 2 :(得分:-1)
尝试将连接传递给mysql_query:
function runQuery($query){
$result= mysql_query($query, $this->connection);
.....
它应该在不传递连接的情况下工作,但是根据项目中的其余代码以及您正在创建的数据库实例,这可能是问题所在。
如果您提供调用runQuery的代码,那么正确答案会更容易。