I’m trying to offload the process of connecting to a database to a DBConfig.php file, as suggested pretty much everywhere, because I’ll need to reuse the code in several files.
The suggestion is always framed as (edited to reflect my actual code):
-------DBConfig.php-------
<?php
$link = mysql_connect('localhost','user','pass');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db_name : ' . mysql_error());
}
?>
-------Parent.php-------
<!DOCTYPE html>
<?php
require_once 'DBConfig.php';
$something = mysql_query("SELECT * FROM `table` LIMIT 0, 30 ");
// This query works fine if the mysql_connect() and
// mysql_select_db() stuff is in this script in place
// of the require_once.
$listofthings = array();
while($temp = mysql_fetch_array($something)){
$listofthings[] = $temp;
}
// Do other things too
?>
But when I try to do mysql_fetch_array($something), it fails with the warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.
Keeping in mind that everything works beautifully if I simply drop the contents of DBConfig.php into the parent script instead of require 'DBConfig.php';…
And also noting that print(require 'DBConfig.php'); //- 1 (PHP is returning a 1 to indicate that it is successfully locating and including the file. See example 5)…
What is going on, and how do I fix it? I am using the default configuration for WAMPServer (Apache 2.4.2, PHP 5.4.3), running on Windows 7 x64.
If this
is literally what you are doing, there is absolutely no way the script can be executed in some other scope. If you were using a
http://URL, it would be the cause but not if you use a relative path like you do.You are not doing any error checking after connecting to your database, nor after the
mysql_query()call, so it’s more likely it’s simply the query breaking. Add proper error checking to your queries and you will know more.Another possibility is if you call
DBConfig.phpinside a function. Functions will mess with your include’s scope. But there’s none in your example, so I’m assuming that is not the issue.