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
Related
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."'");
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");
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.
i am unable to get the last 2 echos to work, even if the update query fails it still displays success. If anyone has any suggestions on this code to be improved on any line, please do!
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}
?>
Thanks in advance!
mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error()."update failed");
and use
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last query failed.
use try catch and try to get the error enable error reporting in php also
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;}
try{
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>"; }
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}catch(Exception $e){
print_R($e);
}
}
use or die(mysql_error()) as it will display mysql error if there is an error with your query.
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error());
Try this:
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'");
if(!idfetch){
die(mysql_error());
}
Do the same for all other queries too.
try this, first count the row count value its great 1 then proceed the login process.
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$count= mysql_num_rows($idfetch);
if($count>0){
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
} } ?>
Use
if(mysql_num_rows($updatequery) > 0) {
// success
} else {
// error
}
$updatequery will always be true (not NULL), until there is an error in your query
I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!