mySQL statement not working inside of php - php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version

Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}

I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

Related

Every entered username and password works in PHP login

I have a problem in my php code. I want to make login system which takes username and password from database. I almost made everything work. But there is one problem.. When you enter name and password/ doesn't matter what, even random/ it logs me in and redirects me to the place i want. How to fix that and make it use only right username and password from database ? I will import my login code file here. Thanks in advance, sorry for my English.
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['uid'];
$query = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $query);
if ($result = mysqli_query($conn, $query))
{
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
}
// If the while loop fails, password/username combo was incorrect
printf("Login failed - Invalid username or password.");
} else {
printf("Login failed, could not query the database.\n");
}
header("Location: panel.php");
?>
First of all, you are WIDE OPEN to SQL Injection, you will want to update that. Its covered in tons of other places, look it up.
But to fix your issue, You are redirecting regardless of your checks. Move this to your while loop:
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
header("Location: panel.php");
}
Having that at the bottom means it gets fired no matter what.
Use mysqli_num_rows
$sql="SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
if ($result=mysqli_query($con,$sql))
{
if (mysqli_num_rows($result)!=0) {
printf("Login success\n");
}else{
printf("Login failed - Invalid username or password.");
}
mysqli_free_result($result);
}
Try this
<?php
function Db(){
$host = "localhost"; // your db settings
$username = "yourusername";
$password = "yourpass";
$db = "users";
$conn = new mysqli($host, $username, $password, $db);
// use mysqli instead mysql_connect, it is outdated I guess
if(!$conn){
die("Could not connect");
}
}
if(isset($_POST['login'])){
$uid = trim($_POST['username']);
$pwd = trim($_POST['password']);
if($uid == ""){
$err[] = "Username is missing.";
}elseif($pwd == ""){
$err[] = "Password is missing.";
}else{ // When validation succeed then make query.
$db = Db();
$uid = $db->real_escape_string($uid); // escape strings from mysql injection
$pwd = $db->real_escape_string($pwd);
$sql = "SELECT * FROM users
WHERE username = '$uid'
AND password = '$pwd'";
$result = $db->query($sql);
if($result->num_rows == 1){
header("location:panel.php"); // login succeed
}else{
$err[] = "Username or password are incorrect";
header("location:login.php"); // login failed
}
}
}
?>
<?php
if(isset($err)):
foreach($err as $loginErr):
echo $loginErr; // Print login errors.
endforeach;
endif;
?>
<!-- HTML login form goes here -->

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

Php - Two-Way Login Form [Admin & User]

I am trying to make a login form which is able to detect whether the user is admin or non-admin. I tried the following but when i run it i get no results:
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$r = mysqli_fetch_array($a);
if(is_array($row))
{
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
}
elseif(is_array($r))
{
$_SESSION["admin"] = $row[id];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
?>
When i insert the username and password for admin it reloads the login form.
UPDATE 1:
The non-admin part is just working fine but the admin part redirects/reloads itself to the login form.
you should check your login post form,should have a code like this:
<form name="loginform" method="post" action="check.php">
if your 'action' vlaue is invalid,the page may refresh.
you should confirm that your login form is posted to the php page you posted.
Try this, lets see what happens.
session_start();
$msg = "";
if(count($_POST)>0){
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$stdCount = mysqli_num_rows($result);//counts the number or rows returned from student table
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$tchrCount = mysqli_num_rows($a);// same but with teachers table
if($stdCount != 0){
$row = mysql_fetch_array($result);
$_SESSION['id'] = $row['id']; //set session for non admin.
}else if($tchrCount != 0){
$r = mysql_fetch_array($a);
$_SESSION['admin'] = $r['id'];
}else{
echo "Username and Password is not Matching.";
}
}//end of the main if
I have not tested this code so dunno if it works or not but I think you got the logic.
use quotes: $row["id"]
"Location: " must be capital.
after calling the "header" function make sure you use "exit".
This code is not tested, but if I understood correctly, should work.
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_student = mysqli_fetch_array($result_student);
$result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_teacher = mysqli_fetch_array($result_teacher);
if(is_array($result_student))
{
$_SESSION["id"] = $row_student["id"];
$_SESSION["name"] = $row_student["name"];
$_SESSION["admin"] = 0;
}
elseif(is_array($result_teacher))
{
$_SESSION["id"] = $row_teacher["id"];
$_SESSION["name"] = $row_teacher["name"];
$_SESSION["admin"] = $row_teacher["id"];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
if(#$_SESSION["admin"]>0)
{ header ("Location: gui-admin.php");
exit;
}
else
{ header("Location: user_dashboard.php");
exit;
}
}
?>
Hope it helps....
But I can guess why you are facing the problem for your code only working for students.
In this -
if(is_array($row))
is_array($row) would always be returning true and the code goes on to execute
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
but $row[id] would be empty because there are no rows matching the criteria, so $_SESSION["id"] would not be assigned and when this is executed -
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
None of the if statements would not be executed because none of them are set. This is my analysis. This could be wrong.
Try the solution below -
You should combine the users table for just querying whether the user is a student or a teacher. You then query the student table or the teacher table depending on the Main "Users" table. Querying for the same username and password to two tables doesnt look good.
You can change the meta tag in my code to header("Location: $url") but I would prefer this so that the request doesnt get cached by the user.
Hope it helps :-
$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection.
$result=mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result))
{
$fetch=mysqli_fetch_row($result);
$_SESSION["id"]=$fetch['userid'];//Just fetching all details
$_SESSION["Name"]=$fetch['name'];//and making session variables for that.
$_SESSION["username"]=$fetch['username'];
$isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.
if($isadmin) //checking whether admin or not
{
$_SESSION["isadmin"]=1;
echo "<meta http-equiv='refresh' content='0;url=adminurl'>"; } //if admin redirect to different url
else{
$_SESSION["isadmin"]=0;
echo "<meta http-equiv='refresh' content='0;url=userurl'>";
}
}
else
{
//Username Password Incorrect
/* Show FORM HERE */
}
First of all, you have to know that's really a bad idea to use your POST data directly in your SQL request, you have to avoid that and to clean your data using a function like mysqli_real_escape_string. Also, you have to secure your passwords and avoid to save it clear into your DB, for that take a look on the best way to store password in database.
For your two SQL requests, you can use mysqli_multi_query like I did in this example where I used the same script to get POST data and show the login form :
<?php
if(count($_POST) > 0){
session_start();
$link = mysqli_connect('localhost', 'user', 'pass', 'db');
if(mysqli_connect_errno()) {
die('db connection error : ' . mysqli_connect_error());
}
function secure_password($password){
// secure your password here
return $password;
}
// escape special characters
$user_name = mysqli_real_escape_string($link, $_POST['user_name']);
// you have to secure your passwords, when saving it of course
$password = secure_password(mysqli_real_escape_string($link, $_POST['password']));
$query = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
$query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";
$is_teacher = FALSE;
if(count($_SESSION)) session_destroy();
// you can use mysqli_multi_query for your two requests
if (mysqli_multi_query($link, $query)) {
do {
if ($result = mysqli_store_result($link)) {
if ($row = mysqli_fetch_row($result)) {
if($is_teacher){
$_SESSION['admin'] = $row[0];
} else {
$_SESSION['id'] = $row[0];
$_SESSION['name'] = $user_name;
}
}
mysqli_free_result($result);
}
if (mysqli_more_results($link)) {
// if we have more results, so it's a teacher record
$is_teacher = TRUE;
}
} while (mysqli_more_results($link) && mysqli_next_result($link));
}
mysqli_close($link);
if(isset($_SESSION['id']))
{
header('Location:user_dashboard.php');
}
elseif(isset($_SESSION['admin']))
{
header('Location:gui-admin.php');
}
// no redirection, show the message and the login form
echo 'Invalid Username or Password!';
}
?>
<form action='p.php' method='post'>
User name : <input type='text' name='user_name'><br>
Password : <input type='password' name='password'><br>
<input type='submit' value='Submit'>
</form>
Hope that can help.

Log in and run query based on a select value

Im trying to use a select box to run different sql to log the user into my site. But for some reason it doesnt work. It "just shows the This user does not exist, please register first if you wish to continue message" that i have at the end.
My plan was just to get the value by using $_POST and storing it in a variable and then just say if that equals this then run this sql to change the value of $databpass and $databuser. (See code for more)
Also for some reason the first if statement works and i can log in. I tried else if but that was the same.
All Help Appreciated thx :D
Please bare in mind that i am fairly new to stackoverflow and php
$username = $_POST ['Username'];
$password = $_POST ['Password'];
$c= $_POST ['ch'];
if ($c=="S")
{
include 'connect.php';
$squery = mysql_query("SELECT * FROM S WHERE Username='$username'" );
$snumrow = mysql_num_rows($squery) or die(mysql_error());
if ($snumrow!=0)
{
while($row = mysql_fetch_assoc($squery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c=="Or")
{
include 'connect.php';
$oquery = mysql_query("SELECT * FROM O WHERE Username='$username'" );
$onumrow = mysql_num_rows($oquery) or die(mysql_error());
if ($onumrow!=0)
{
while($row = mysql_fetch_assoc($oquery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c== "C")
{
$query = mysql_query("SELECT * FROM C WHERE Username='$username'" );
$numrow = mysql_num_rows($query) or die(mysql_error());
if ($numrow!=0)
{
while($row = mysql_fetch_assoc($query)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($username==$databuser&&$password==$databpass)
{
$_SESSION['username']=$username;
setCookie("sessionUsername", $username, time()+ 3600);
header("Location: memberprofile.php");
}
else
echo "Incorrect pass";
}
else
die("This user does not exist, please register first if you wish to continue");

PHP/MySQL mysql_num_rows not returning values

I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

Categories