I have recently started creating a website in PHP. Most of my code is working however I have found a problem that i am having trouble correcting.
I have a page where there are lots of calls to the database. at the top of my page I am connecting and using a SELECT to get some information on the related product.
At the bottom of the page I am connecting again getting comments on the related product.
My code is very lengthy so it is hard for me to show in here but the basics of this code are as follows:
PHP CODE
SELECT's
UPDATE's
HTML
TABLE's
IMAGE's
ect...
PHP
SELECT's
My code successfully runs all of my code when I first load up the page however when I click a button to update a table (in the top section of the code) the update is processed however the comments section at the bottom of the page brings back the following errer:
“no database selected.”
Both selects from the top of the page and the bottom of the page are connection to the same database and same table. Also the comments section that is bringing back the error works fine before I click the update button.
The code where my code says the error is happening is:
$commResult = mysql_query("SELECT u.id, u.USERNAME, c.COMMENT, c.DATE_ADDED, c.ACTIVE FROM USERS u, COMMENTS c WHERE c.box_id = $boxId ORDER BY c.DATE_ADDED DESC") or die (mysql_error());;
while ($row = mysql_fetch_array($commResult))
{
//Do processing here.
}
My code for connection to the database. This is in a seperate file and i use a require_once(config.php); to call it at the top of every page that my code needs to connect to the database.
$username = "user";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("databasename",$dbhandle)
or die("Could not select databasename");
I believe you may be opening a MySQL connection at the top of the script, closing it and reopening it without forgetting to select the database.
If you’re using the old mysql_ functions (which you shouldn’t really be using for new code anymore, take a look at MySQLi and PDO) then you may have forgotten this line of code:
Or, if you’re using “raw queries”, you may be missing this line:
Although on the same script it’s probably not worth closing the database connection, it might be a better idea to keep it open throughout the script.