I have a PHP script that I wrote, and one of the pages connects and executes perfectly, but the other gives me the following error. I am using PHP 5.3.6 on a MAMP installation:
Access denied for user ''@'localhost' to database 'premind'
Here’s the page throwing the error:
<html>
<head><title>User CP</title></head>
<body>
<form name="logoutbutton" method="post" action="logout.php">
<input type="submit" name="logout" value="Log out" />
</form>
<h1>User Control Panel</h1>
<h2>Below is a list of current assignments:</h2>
<?php
include('/Applications/MAMP/htdocs/premind/includes/vars.php');
session_start();
if (isset($_SESSION['emailaddress'])) {
mysql_select_db($db_name) or die(mysql_error());
$sql4 = 'SELECT `aname`, `date`, `useremail`, `aid` FROM `data`';
$result4 = mysql_query($sql4) or die("<br />" . mysql_error());
$countrows2 = mysql_num_rows($result4);
if (!$result4) {
echo "Cannot show assignments!";
}
while ($row = mysql_fetch_array($result4)) {
if ($row['useremail'] == $_SESSION['emailaddress']) {
echo $row['aid'].". ".$row['aname']." -- ".$row['date']."<br />";
echo "<br />";
}
elseif ($countrows2 == 0) {
echo "<h1>No assignments found!</h1>";
}
}
if ($countrows2 == 0) {
echo "<h1>No assignments found!</h1>";
}
}
else {
header('Location: notloggedin.php');
}
?>
<br />
<br />
<h2>Submit an assignment:</h2>
<form name="submitass" method="post" action="submitassignment.php">
<table>
<tr>
<td><p>Assignment name:</td><td></p><input name="aname" type="text" id="aname" /></td>
</tr>
</table>
<table>
<tr>
<td><p>Due date: (IN YEAR, MONTH, DAY FORMAT)</p></td><td><input name="date" type="text" id="date" /></td>
</tr>
</table>
<br />
<h2>Example of date: 2012-01-05</h2>
<br />
<input type="submit" name="submitass" value="Submit!" />
</form>
<br />
<br />
<h2>Delete and assignment:</h2>
<p>To delete an assignment, enter the number that you see before the assignment name above.</p>
<form name="deleteass" method="get" action="deleteassignment.php">
<p>Assignment ID: </p><input type="text" name="assid" id="assid" />
<input type="submit" name="deleteass" value="Delete!" />
</form>
</body>
</html>
Here’s the vars.php file:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="premind"; // Database name
$tbl_name="members"; // Table name
?>
You are missing the mysql_connect() call.
You are saying that you called it in another file which redirected to this page, but even though it was connected in the previous page, it is not connected in this page. So you have to call mysql_connect separately on this page, or include the file that does the calling.