How do I validate this php form? - php

I have a simple html form that looks like this
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
What I need to do with this is check the values that are submitted in this form against those in a simple database I have created. The database is name is userdb, and in it I have created a simple table called 'users', with two columns called name and password.
I am able to connect to the database correctly with
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Now I'm confused with (probably the most important bit) where I have to validate the form against some values in the database.
I have created a name and password entry in phpmyadmin, for name='eric' and password='123456'.
I'm just not sure how to check it using the form?
Is it something like this?
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
$name and $pw are values that I got from the form name attributes.
It tells me I have undefined variables though so obviously I've got it wrong here.
Any help?
*edit here is the full code:
index.php
<html>
<head>
<style>
#main
{
width: 700px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="main">
<?php
$name = "";
$pw = "";
?>
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
</div>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
?>
</body>
</html>

Your POST variables are in the wrong file. Take them out of index.php and place them in insert.php as so:
You're also storing passwords in plain text, which is not recommended. Use PHP's password_hash() function if your PHP version is 5.5. Otherwise, use crypt() or bcrypt()
Sidenote: There is a password compatibility pack available here for the password_* functions.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
?>
</body>
</html>
If you want to check for successful insert, do:
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
if (mysqli_query($con,$sql))
{
echo "Database updated successfully";
}
else
{
echo "Error: " . mysqli_error($con);
}
Footnotes:
For added security, change:
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
to:
$name=mysqli_real_escape_string($con,$_POST['name']);
$pw = mysqli_real_escape_string($con,$_POST['pw']);
Login method: (Sidenote: Use the password storage methods shown at the top if possible).
If you want to use it as a login method, you can use something to the effect of:
$con = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$user = mysqli_real_escape_string($con,$_POST['name']);
$pass = mysqli_real_escape_string($con,$_POST['pw']);
$query = "SELECT * FROM your_table WHERE name='$user' AND password='$pass'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["name"]==$user && $row["password"]==$pass){
echo "You are a validated user.";
}
else{
die("Sorry.");
}

$sql="SELECT * FROM userdb WHERE name='$name' LIMIT 1";
Then fetch the result and check if the password is equal to the password you have.
Next thing you want is to return something, and also to actually log the user in do:
$_SESSION['userid'] = $userid;
Or store whatever you want^. Then check if that exists in all your other pages to determine if the user is logged in.
EDIT: Also it seems like it's needed to add - you're not storing your passwords securely, and you're also not sanitizing your strings properly (against SQL injections). Might want to look into that ^_^.
EDIT 2: Oh yeah, for your problems - variables are undefined because you have to get them using $_POST['']. Inside the '', put the name of the variable you're expecting. $_POST['name'] to get the name, for example.

I would recommend you to use the PHP Data Objects handle the data.
I am not quite sure what exactly you want. You want to make a login page or a signup page?
//connect database
$dsn='mysql:dbname=userdb;host=localhost';
$dbu=''; //YOUR DATABASE USERNAME GOES HERE
$dbp=''; //YOUR DATABASE PASSWORD GOES HERE
try {
$dbh=new PDO($dsn,$dbu,$dbp);
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
}
if it's a login page, using this:
//check name and password
$sth=$dbh->prepare('SELECT 1 FROM users WHERE name = ? AND password = ?');
$sth->execute(array($_POST["name"], $_POST["pw"]);
$row=$sth->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 1){
echo "Correct name and password";
} else {
echo "Wrong name or password";
}
if it's a signup page, using this:
//insert name and pass
$sth=$dbh->prepare('INSERT INTO users (name, password) VALUES (?,?)');
$sth->execute(array($_POST["name"], $_POST["pw"]);

Related

Insert into my local sql server

I'm trying to insert into my local sqlserver. The problem is that it doesnt seems to run php code. It opens page in browser with all my code:
Html
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
Php
<?php
$servername = "(local)\sqlexpress";
$username = "sa";
$password = "1234";
$dbname = "MyCalendar";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customermaster(code, name, email)
VALUES ('1234', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I'm begginer on this. Souldnt i take only the exception if something will go wrong?
You can not directly open php files. You need to install a local server on your computer for your php codes to be executed. Try XAMPP it is easy to install.
You need to first set up a web server. AppServ can recommend about it is simple and fast. Check the incoming POST when we come to your code.
Example :
if(extract($_POST)) {
$sql = "INSERT INTO customermaster(code, name, email) VALUES ('1234', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Also : After installation is complete in the url portion of the run, type http://localhost.

Inserting data into SQL table from HTML form

A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!con) {
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')) {
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.
You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.
Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!$con){
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')){
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
mysqli_stmt_execute($stmt);
echo "Data inserted";
}
else {
echo "Error";
}
mysqli_close($con);
//header("refresh:2; url=form.html");
?>
I think it should work, if not let me know.
Try this :
<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Having trouble with inserting query after program checks username availability using ajax

I'm having trouble inserting my query into the database after the program checks the username availability on blur using ajax to check if the username is available for register or not. After it checks the username availability, it always insert some empty queries in my database.
Here is the sample output for more details:
But the problem is when it displays username available it will automatically inserts an empty query into the database.
This will insert into the database after it checks the availability of the user:
I want the insert query to be inserted when the user submits or when he/she clicks the register button. The availability of the username is for checking only. Is there a problem with my code?
Here is the code:
Sample.php FILE
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="text" placeholder="Username" id="username" name="username" class="form-control" >
<span id="availability" style="color:green;"></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" >
<input type="submit" id="signup" name="signupsubmit" class="btn btn-info form-control" value="Register">
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
</html>
I use ajax for checking the username availability inside the script here:
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
The process file for checking username and inserting a query.
SampleProcess.php FILE
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"]))
{
$sql = "SELECT * FROM tablereminders WHERE username ='".$_POST["username"]."'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0 )
{
echo"<span class=\"text-danger\">Username not available</span>";
echo'<script>document.getElementById("username").focus();</script>';
}
else
{
//In this else condition the query will be inserted in the
//database after the user clicks the register button, but it will insert right
//after the program check the availability
echo"<span class=\"text-success\">Username available</span>";
//Problem inserting my query here
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE)
{
echo "<script type='text/javascript'>alert('New record created successfully');</script> ";
echo "<script>setTimeout(\"location.href = 'LoginReminder.php'\", 0)</script>";
}
}
}
?>
In the else condition after checking mysqli_num_rows I put my insert query there to perform when the user clicks the register buton. Is there a problem with my if-else condition or is it about the AJAX function inside the Sample.php file, Should I use GET or POST method? Either way I tried it but it doesn't correct my problem here. Please help.
Try this ;)
There are two things
Check username availability.
Submit the form and create a record.
1. Check username availability.
For this, you have done all the code you need to modify code like this:
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"])){
$sql = "SELECT * FROM tablereminders WHERE username ='" . $_POST["username"] . "'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
echo '<span class="text-danger">Username not available</span>';
echo '<script>document.getElementById("username").focus();</script>';
}else{
echo '<span class="text-success">Username available</span>';
}
}
2. Submit the form and create a record.
Now create new ajax call to some other file to insert record which submits form data on some button click event.
This you can do same you done in case of username availability.
Code sample to insert record:
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE){
echo '<script type="text/javascript">alert("New record created successfully");</script>';
echo '<script>setTimeout(function(){ location.href = "LoginReminder.php"}, 0);</script>';
}
Remember 2 things before inserting new record in database:
Validate user data.
Escape user data may be with this function mysqli_real_escape_string OR you can use prepared statement and bind params.

Showing the users' username on screen. Getting 'Undefined Index' error

Okay, so I'm trying to display the users first name as a greeting message on index.php like, 'Hello, (users first name), but im pretty new to all this php stuff so i really cant figure out how to do this. I tried to follow a short tutorial, but whenever i try to print the first name with 'print $_POST['first_name'] i get a undefined index error.... Might be a stupid question, but i just cant figure it out.
Here's my db_connect.php if it matters at all:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "Byt til Nyt";
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo "Could not connect to database.";
}
mysql_select_db("$db");
?>
Here's a short version of my register.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<?php
include('includes/db_connect.php');
if (#$_GET["op"] == "reg") {
$bInputFlag = false;
foreach ($_POST as $field) {
if ($field == "") {
$bInputFlag = false;
} else {
$bInputFlag = true;
}
}
if ($bInputFlag == false) {
die("Der opstod et problem med dine oplysninger. Gå tilbage og prøv igen.");
}
$q = "INSERT INTO 'users' ('first_name','last_name','email','username','password')" . "VALUES ('" . $_POST["username"] . "'," . "PASSWORD ('" . $_POST["password"] . "')," . "'" . $_POST["email"] . "')";
$r = mysql_query($q);
if (!mysql_insert_id()) {
die("Der opstod en fejl. Du er ikke blevet tilføjet til databasen.");
} else {
Header("Location: register.php?op=thanks");
}
} elseif (#$_GET["op"] == "thanks") {
echo "<h2>Tak fordi du registrerede!</h2>";
}
?>
</head>
<body>
<form method="post" action="includes/verify.php" name="register">
//recaptcha script here
<label>First name</label>
<input type="text" name="first_name" placeholder="Your first name" required><br>
<label>Last name</label>
<input type="text" name="last_name" placeholder="Your last name" required><br>
//some more input fields and stuff
And here's a short version of my index.php:
<?php
session_start();
include("includes/functions.php");
include("includes/db_connect.php");
?>
<!DOCTYPE html>
<html lang="dk">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<title>
Byt til Brugt
</title>
<link rel="stylesheet" href="index.css">
</head>
<body background="http://i.imgur.com/urLzQr5.jpg" bgcolor="navy">
<div class="menu">
<p>Velkommen, <?php if (isset($username)) {
print $_POST['first_name'];
}
?>
</p>
So, what is the problem?? :/ Any help would be VERY appreciated, I've been trying to fix this for 2 days now.... Just say if you need my login.php or anything else (: Thanks a lot! And sorry for my bad English..
$_POST['first_name']
is probably not set, try
<?php if (isset($_POST['first_name'])) {
print $_POST['first_name'];
}
?>
You don't have the user POSTing to your index page, therefor the $_POST variable is empty when you try to access it.
Your register form posts to includes/verify.php
The variable $_POST is only populated for you if the user submits a form using the POST method. So you should NEVER expect it to contain data, always check it first (!empty($_POST) at the least).
What you are probably intending to do is retrieve the name from the database using their username. (Probably stored in the session?)
Once you have populated the variable then you simply echo out that variable when you need it and you will get the first name they entered when signing up.
Additionally, your signup page won't work as intended for the same reason. You are posting to includes/verify.php and judging from your code it looks like your verify page redirects the user back to register.php?op=reg which means you just lost all of your POST data unless you are using javascript to post back to register.php?op=reg (but that isn't needed)
Also, your MySQL is wrong. You are trying to insert into 5 fields
'first_name','last_name','email','username','password'
and you are only passing 3 values
'username', 'password', 'email'
You should be passing 5 values and the order should match the column list. If you set a default value for username and password then this might not cause a MySQL error but your data will not match up to the intended field.
(Username into first_name, password into last_name, email into email, nothing in username, nothing in password)
You mention that you are following a tutorial, so perhaps it's best to just look for another tutorial. Maybe one that is a little more updated considering you should avoid using mysql_connect or mysql_pconnect as a database method.

PHP: 'Sorry, you must enter a valid username and password to log in' error appearing even though the select statement from the database is correct

I am having some problems with login validation using PHP. I am selecting the correct data from the database (have checked this using phpmyadmin) and if I echo a SELECT* the data shown is correct.
However, when I enter the correct login details, the script is skipping to the error message 'Sorry you must enter a valid username and password to log in'.
I have searched for everything I can think of to try and fix this (printing results of queries etc) but no luck. The code is below:
<?php
$link = mysql_connect('localhost:8889', 'root', 'root', 'help_me_be_healthy')
or die('Could not connect: ' . mysql_error());
//mysql_select_db('help_me_be_healthy') or die('Could not select database');
$dbc = mysql_select_db('help_me_be_healthy', $link);
if (!$dbc) {
die("Database could not be selected" . mysql_error());
}
// Start the session
session_start();
// Clear the error message
$error_msg = "";
// If the user isn't logged in, try to log them in
if (!isset($_SESSION['user_id'])) {
if (isset($_POST['submit'])) {
// Connect to the database
$dbc = mysqli_connect('localhost:8889', 'root', 'root', 'help_me_be_healthy');
echo one;
// Grab the user-entered log-in data
$username = mysqli_real_escape_string($dbc, trim($_POST['username']));
//echo $_POST ['username'];
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
//echo $_POST ['password'];
if (!empty($_POST['username']) && !empty($_POST['password'])){
// Look up the username and password in the database
$query = "SELECT `user_id`, `username` FROM `users` WHERE `username` = '$username' AND `password` = SHA('$password')";
$data= mysql_query($dbc,$query);
if (mysqli_num_rows($data) == 1) {
// The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);
echo four;
}
else {
// The username/password are incorrect so set an error message
$error_msg = 'Sorry, you must enter a valid username and password to log in.';
echo five;
}
}
else {
// The username/password weren't entered so set an error message
$error_msg = 'Sorry, you must enter your username and password to log in.';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mismatch - Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h3>Mismatch - Log In</h3>
<?php
// If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in
if (empty($_COOKIE['user_id'])) {
echo '<p class="error">' . $error_msg . '</p>';
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Log In</legend>
<label for="username">Username:</label>
<input type="text" id = "username" name="username"
value="<?php if (!empty($username)) echo $username; ?>" /><br />
<label for="password">Password:</label>
<input type="password" id = "password" name="password" />
</fieldset>
<input type="submit" value="Log In" name="submit" />
</form>
<?php
}
else {
// Confirm the successful log-in
echo('<p class="login">You are logged in as ' . $_COOKIE['username'] . '.</p>');
}
?>
</body>
</html>
Any help would be much appreciated!
You are mixing mysql_query and mysqli_num_rows. Either use mysql_, OR mysqli_, but not both. They are NOT interchangeable.
#[Niet the Dark Absol] is correct that you cannot interchange mysql_ and mysqli_.
The offending piece of code is:
$query = "SELECT `user_id`, `username` FROM `users` WHERE `username` = '$username' AND `password` = SHA('$password')";
$data= mysql_query($dbc,$query);
Change mysql_query to mysqli_query.
And you can remove the database connection calls above session_start() -- they aren't needed since you are doing a perfectly good call to mysqli_connect() after checking to see if the user is already logged in.
$query = "SELECT `user_id`, `username` FROM `users` WHERE `username` = '$username' AND `password` = SHA('$password')";
$data= mysql_query($dbc,$query);
if (mysqli_num_rows($data) == 1) {
Your problem is in this area of code. Try using mysql_num_rows instead mysqli, and try to output the value of mysql_num_rows() to see if it's 1.

Categories