这个问题已经困扰我好几个小时了,我快要放弃了。
我的项目有三个相关文件:
dbconfig.php
register.php
testmysql.php
dbconfig.php有如下函数:
public function connString()
{
$connString['host'] = $this->host;
$connString['username'] = $this->username;
$connString['password'] = $this->password;
$connString['database'] = $this->database;
return $connString;
}
我在testmysql.php
中这样做,它工作得很好:
require('dbconfig.php');
$dbObject = new dbconfig();
$conn = $dbObject->connString();
mysql_connect($conn['host'],$conn['username'],$conn['password']) or die(mysql_error());
mysql_select_db($conn['database']) or die(mysql_error());
但是当我在register.php
中做同样的事情时,它失败了:
<div class="div_texbox">
<select id="field1" name="field1" class="textbox">
<option value="0">Select</option>
<?php
require('dbconfig.php');
$dbObject = new dbconfig();
$conn = $dbObject->connString();
mysql_connect($conn['host'],$conn['username'],$conn['password']) or die(mysql_error());
mysql_select_db($conn['database']) or die(mysql_error());
$result = mysql_query("SELECT * FROM table") or die ('error selecting');
while ($row = mysql_fetch_array( $result ))
{
echo "<option value='"" . $row['ID'] . "'">" . $row['value'] . "</option>";
}
?>
</select>
</div>
当我说"它失败了"的细节:Field1
是一个选择框,应该填充,但它没有,没有进一步的字段在表单显示(大概是因为die
)。我尝试安装一个PHP调试器来查看正在抛出的消息,但无法获得一个工作。如果我硬编码连接参数,一切都可以工作。$conn
的var_dump
显示它在所有正确的索引上保存了所有正确的值(testmysql.php
也有效)。
此外,如果一些故障排除使mysql_connect
似乎失败
我分析了渲染页面的HTML代码,以查看PHP脚本的输出,如下所示:
( ! ) Fatal error: Cannot redeclare class dbconfig in C:'wamp'www'site'dbconfig.php on line 10
Call Stack
#TimeMemoryFunctionLocation
10.0005698544{main}( )..'register.php:0
21.2728763824require( 'C:'wamp'www'site'dbconfig.php' )..'register.php:106
dbconfig构造函数
public function __construct($config = NULL)
{
if ($config != NULL)
{
$this->host = $config['hostname'];
$this->database = $config['database'];
$this->username = $config['username'];
$this->password = $config['password'];
}
else
{
$this->host = $this->defaultConfig['hostname'];
$this->database =$this->defaultConfig['database'];
$this->username = $this->defaultConfig['username'];
$this->password = $this->defaultConfig['password'];
}
}
看起来您不止一次包含了dbconfig.php
,这导致了不能重新声明类致命错误。
更改
的引用require('dbconfig.php')
require_once 'dbconfig.php';
当你在它,停止使用or die()
和切换到PDO和参数化语句。