Reputation: 1
Have been trying to figure out for about an hour why, when I enter log in information on the index page, then click submit, it says "No database selected" on the Login.php page. Any advice would be much appreciated, thanks!
The connect.php file
<?php
$host= "127.0.0.1";
$username = "root";
$password = "";
$db = "users";
mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($db);
?>
The login.php file
<?php
session_start();
//Login Script
//Make sure have access to database
include_once("connect.php");
//If the post of the username (username has been submitted on login form)
if (isset($_POST["username"])) {
//set variables
$usernmame = $_POST["password"];
$password = $_POST["password"];
//Select the column from the users table where the username is the username entered aps same for password
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
//Run quety
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
echo "Success";
}
else {
echo "Again";
}
}
The index file
<?php
session_start();
?>
<head>
<title>Login test</title>
<link rel="stylesheet" type"text/css" href="style.css" />
</head>
<div id="wrapper">
<h2>test log in</h2>
<?php
//If not logged in, display login formThe
if(!isset($_SESSION["uid"])) {
echo "<form action='Login.php' method='post'>
Username: <input type='text' name='username' />
Password: <input type='password' name='password' />
<input type='submit' name='submit' value='Login'/>";
}
else {
echo "<p>You are logged in as ".$_SESSION['username']." <a href='Logout.php'>Log out</a>";
}
?>
Upvotes: 0
Views: 102
Reputation: 657
I could be wrong but I don't believe the mysql_connect
function allows you to select the database. Try the following in your connect file. You should also consider switching to the MYSQLI functions which support selecting a database on connect.
mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($db);
Upvotes: 0
Reputation: 17289
First of all you should stop using mysql_*
functions.
But just to try to help you pass this obstacle for now try this way:
$db_link = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($db, $db_link);
and then always use that $db_link
like:
$result = mysql_query($sql, $db_link) or die(mysql_error());
Upvotes: 1
Reputation: 2101
The mysql_connect
(note the deprecation warning on the page) function doesn't let you specify a default database. However the mysqli_connect
function does.
Also the return value of mysql_select_db
should be checked, to see if the database is actually selected.
Upvotes: 0