This has been baffling me for a few hours now and I’m reaching the point of giving up.
My project has 3 relevant files:
dbconfig.php
register.php
testmysql.php
dbconfig.php has this function:
public function connString()
{
$connString['host'] = $this->host;
$connString['username'] = $this->username;
$connString['password'] = $this->password;
$connString['database'] = $this->database;
return $connString;
}
I do this in testmysql.php and it works perfectly:
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());
But when I do the same thing in register.php, it fails:
<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>
Details on when I say ‘it fails’:
Field1 is a select box that is supposed to populate, but it doesn’t and no further fields in the form show up (presumably because of the die).
I tried installing a PHP debugger to see the message being thrown but could not get one working.
If I hardcode in the connect parameters, it all works.
A var_dump of $conn shows it to be holding all the right values at all the right indices (also evident in the fact that testmysql.php works).
Also, it some troubleshooting made it seem that it is failing at mysql_connect
I analyzed my HTML code of the rendered page to see the output of the PHP script and this is what it shows:
( ! ) 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 constructor
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'];
}
}
Looks like you’re including
dbconfig.phpmore than once which is causing the cannot redeclare class fatal error.Change any reference of
to
While you’re at it, stop using
or die()and switch to PDO and parameterised statements.