I have been through quite some different codes on this site. To find what wrong with my code. Basically I just want to search in a table and test the result. I wrote something like this:
<?php
ob_start();
session_start();
$conn = new mysqli('localhost','username','password','mytable');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
if(mysql_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
And I get always the message :
"User not found." and "password not found."
when I know the username and password are in the table...
No I'm quite knew with PHP/MySQL so there might be something quite big right in front of my face and I can't see it!!!!
Can somebody help please. Thanx.
Takes less than a second to spot. (If you had error reporting on it would take even less than that)
1) Your connection is mysqli but your query call is mysql
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
2) Value of $valuetotest is a string value and needs to be within quotes in your query. Should be like
SELECT id FROM members WHERE UserName = 'hellohi'
And not like
SELECT id FROM members WHERE UserName = hellohi
And Oh, How can I prevent SQL injection in PHP?
<?php
$result = mysqli_query("SELECT `id`, `Password` FROM `members` WHERE `UserName` = '$valuetotest'");
if(mysqli_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
You are selecting a text so you should use ' ' Symbols in your Select statement.
Like this:
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = '$valuetotest'");
$result = mysql_query("SELECT id FROM members WHERE UserName = '".$valuetotest."'");
Related
I have designed a admin login page. The if condition is working but else condition is not. After putting wrong username or password it shows blank on the same page.
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count == 1)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
You used mysql_error(); which is causing the error of blank page.
Use the below code will fix your problem.
$sql = mysqli_query($DBCONNECT,$query);
$count = mysqli_num_rows($sql);
Remove or die(mysqli_error($link)) from your code that will work fine for you.
Note: mysqli_num_rows can be used for Procedural style only not for object oriented style.
Can you try with this code? Difference is putting if($count) instead of if($count==1)
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
Mysqli Also make result as object so you can do this :
$sql = mysqli_query($con, "SELECT * FROM users WHERE userid='$userid' and pass='$pass'") or die(mysqli_error());
your mysqli_error only will show if statement wrong and i don't think you will put wrong statement but good in development.
then you can check if statement works by if and put this :
echo $sql->num_rows;
can put in variable :
$count = mysqli_num_rows($sql) to $count = $sql->num_rows
or
if($sql->num_rows == 0) {
// here your blank result for error
} else {
// show result here.
}
Link : Check PHP Site Mysqli Num Rows Result
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!";
?>
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.
If i enter wrong password it shows 'Wrong username or Password' but if enter wrong username and correct password it shows nothing. Why ? what should i change in the code?
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
if($row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
}
mysql_close($dbc);
?>
Because if you enter the wrong username the query returns nothing.
Then you don't get into the while loop.
You could change the query :
$result = mysql_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".addslashes($password)."'");
Then use mysql_fetch_row() only once (remove your while loop).
EDIT
<?php
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
$name = $_POST['username'];
$password = hash_password($_POST['pwd']);
$dbc = mysqli_connect('localhost', 'username', 'password') or die();
mysqli_select_db("dbname") or die();
$mysql_result = mysqli_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".$password."'");
$result = mysqli_fetch_row($mysql_result);
mysqli_close($dbc);
if(!$result){
echo "Wrong username or password.";
}else{
var_dump($result);
echo "Successfully logged in.";
}
?>
EDITED for usage of MySQLi as mysql is deprecated since PHP 5.5
EDITED as for plaintext passwords.
It's never a very good thing to store passwords in plaintext in the database as they can be stolen in case of sql injection.
A way to protect your users password is to hash them, below is a basic implementation :
First create a function to hash a password :
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
Then replace your third line $password = $_POST['pwd']; with this one : $password = hash_password($_POST['pwd']);
Here you go! (Just remember to use that same function on the password when you create the user account)
This should work correctly:
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
$row= mysql_fetch_array($result)
if($row && $row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
mysql_close($dbc);
?>
your previous code didn't show anything becasue row = mysql_fetch_array($result) were not finding any record, and so returning immediately false (and exied the while)
Seems like you enter a username that does not exist in that table.
Remove your while loop. Just say:
$result = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE uname = '".mysql_real_escape_string($name)."' AND pword = '".mysql_real_escape_string($password)."'"));
if ($result) {
// Successfully logged in
} else {
// Login failed
}
Keep in mind that the mysql_real_escape_string is very important when accepting user input to avoid SQL injection.
Since you are authenticating a user, record must be unique.
Thus, you shouldn't be looping through anything:
Get rid of the loop and change your conditions
$row = mysql_fetch_array($result);
if($row['uname']==$name && $result){
if($row['pword']==$password){
echo 'Successfully logged in <br />';
}else{
echo 'Wrong Password';
}
}else{
echo 'No record found';
}
mysql_close($dbc);
I refactored your code for this one. I recommend use mysql_fecth_row instead mysql_fetch_array beacause you need just one row.
<?php
// get, validate and clean your input variables
$name = isset($_POST['username']) ? addslashes($_POST['username']) : '';
$password =isset($_POST['pwd']) ? addslashes($_POST['pwd']) : '';
// make your data base connection
$dbc = mysql_connect('localhost', 'root', '') or die();
mysql_select_db("test_mysql") or die();
// building the sql query and getting the result (remember filter by username and password)
$result = mysql_query("SELECT * FROM tb_usuario WHERE uname = '$name' AND pword = '$password'") or die(mysql_error());
// using mysql_fetch_row (remember that just one user must match in the data base if not something is wrong in register ...)
$row = mysql_fetch_row($result);
// remember 0 => id, 1 => uname, 2 => pword
if (is_array($row)) {
echo "Welcome {$row[1]}";
} else {
echo 'Wrong username or password';
}
// close your connection
mysql_close($dbc);
I'm very new to using MySql and am having trouble retrieving values from my database. I was under the impression that i was going about it the correct way but my echo statements don't print anything.
I'd appreciate some help. My code is below. I know i'll have to add security later on like sanitizing user input.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPass = sha1($password);
if ((!isset($email)) || (!isset($password))) {
//Visitor needs to enter a name and password
echo "Data not provided";
} else {
echo "Received details $email and $password <br/>";
// connect to mysql
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
echo "Connected to phpmyadmin <br/>";
}
}
// select the appropriate database
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
echo "Cannot select database.";
exit;
} else {
echo "DB Selected";
}
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
$userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $userdata[3];
echo $userdata['firstName'];
if ($count > 0) {
echo "<h1>Login successful!</h1>";
echo "<p>Welcome.</p>";
echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
// visitor's name and password combination are not correct
echo "<h1>Login unsuccessful!</h1>";
echo "<p>You are not authorized to access this system.</p>";
}
?>
I believe the problem is that you call twice the *fetch* family function which will cause the $userdata to be empty.
From the documentation mysql_fetch_row will fetch the next row and move the internal data pointer ahead. So when you call mysqli_fetch_array($result, MYSQLI_BOTH) and I suppose the user/password is unique there is nothing to retrieve. Also another mistake you did is that your SELECT doesn't retrieve the actual user data, but just the count number for the user/password combination. So your userdata will be always incorrect, even if you fetch the data right.
So change your query to something like that:
$query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";
Then use mysql_fetch_array to check if the entry exist and then retrieve the user data.