Reputation: 108
I'm opening up a project from last year and figured I'd try MAMP on the new computer, seemed kinda cool.
Looks like it's all running, PHP works, and I rebuilt the database in phpMyAdmin.
After adding some test data to the tables, I made a simple test (see files below), but I couldn't retrieve anything from the database.
When I load test-basic.php it says "Connected to db. Selected database. Found Nothing =("
But I tested the string in phpMyAdmin (for the 'likeiwassaying' database) and it returned the results
I feel sooooo close (and have been banging my head on this for hours). Am I missing something right under my nose?
Any troubleshooting suggestions appreciated,
Justin
config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = 'testpassword';
$dbdatabase = 'likeiwassaying';
$config_sitename = 'Cully Mail';
$config_author = 'jk';
$config_basedir = 'http://localhost:8888/cullymail/';
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
if (!$db) {
die('Could not connect: ' . mysql_error());
} else {
echo 'Connected to db. ';
}
$db_selected = mysql_select_db($dbdatabase, $db);
if (!$db_selected) {
die ('Can\'t use: ' . mysql_error());
} else {
echo 'Selected database. ';
}
mysql_close($db);
?>
test-basic.php
require("config.php");
function test() {
$q = 'SELECT * FROM contacts;';
$result = mysql_query($q);
$numrows = mysql_num_rows($result);
//If it is found (if any row comes back)...
if($numrows == 0) {
echo "Found nothing =(";
} else {
echo "found something";
}
}
test();
?>
Upvotes: 1
Views: 102
Reputation: 270677
You're closing your database connection before executing your function test()
. You close the connection at the end of config.php
, meaning that by the time the function is defined in test-basic.php
the db connection already no longer exists and further queries will fail.
You don't usually need to call mysql_close()
explicitly, unless you have a need to regain memory resources early. PHP will close down the connection when the script completes.
$db_selected = mysql_select_db($dbdatabase, $db);
if (!$db_selected) {
die ('Can\'t use: ' . mysql_error());
} else {
echo 'Selected database. ';
}
// Everything is good so far. you're ready to execute queries, but...
// Don't do this!!!
mysql_close($db);
Upvotes: 2