"mysqli_num_rows" struggles with the output of "mysqli_query" - php

I made a simple Login Form there are some errors in the code I guess.
Everything is working fine but I'm struggling with the MySQL(mysqli) Query part.
But here is my code first:
<?php
session_start();
if(isset($_SESSION['acuser']))
{
redirectpage();
}
else
{
if($_POST)
{
if(isset($_POST['button']) && ($_POST['username']) && ($_POST['password']))
{
$db = 'datenbank';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$connection = mysqli_connect($dbhost,$dbuser,$dbpass);
$selection = mysqli_select_db($connection,$db);
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
$password = mysqli_real_escape_string($connection, (htmlspecialchars($_POST['password'])));
$password = md5($password);
if($connection)
{
if($selection)
{
$queryuser = "SELECT * FROM main WHERE Username = '$username'";
$result = mysqli_query($connection, $queryuser);
$checkuser = mysqli_num_rows($result);
if($checkuser)
{
$querypass = "SELECT * FROM main WHERE Username = '$username' AND Password ='$password'";
$resultpass = mysqli_query($connection,$querypass);
$checkpass = mysqli_num_rows($resultpass);
if($checkpass)
{
$data = mysqli_fetch_array ($resultpass);
$_SESSION["acID"] = $data["Id"];
$_SESSION["acUSERNAME"] = $data["Username"];
$_SESSION["acPASSWORD"] = $data["Password"];
$_SESSION["acEMAIL"] = $data["Email"];
}
// Some else stuff
?>
I guess there is something wrong with "mysqli_query()" and "mysqli_num_rows()"!
"Mysqli_num_rows()" can't handle the output of "mysqli_query()" somehow!
Maybe i will find an answer here

Not sure if this is the problem:
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
is the username the same as the password in the database?

Related

Can't update database using php and Mysql

I am trying to update a user password in database with the following code
<?php
session_start();
if( isset($_SESSION['user']) ){
}
else
{
header("location: index.php");
}
$host = "localhost";
$username = "xxxx";
$password = "xxxxx";
$db_name = "auth_db";
$tbl_name = "users";
$link = new mysqli("$host", "$username" , "$password", "$db_name");
if(mysqli_connect_error())
{
die('Connect Error ('.mysqli_connect_errno().')' .msqli_connect_error());
}
$username = $_SESSION['user'];
$pwd = $_POST['oldpass'];
$pwd1 = $_POST['newpass'];
$pwd2 = $_POST['newpass1'];
if($pwd1 !== $pwd2)
{
Print '<script>alert("New Passwords do not match");</script>';
Print '<script>window.location.assign("pwd.php");</script>';
}
$query = mysqli_query($link, "SELECT * from users WHERE username = '$username'");
$user_exist = mysqli_num_rows($query);
$tbl_user = "";
$tbl_password = "";
$password = 0 ;
if($user_exist > 0)
{
while($row = mysqli_fetch_assoc($query))
{
$tbl_user = $row['username'];
$tbl_password = $row['password'];
$password = password_verify($pwd, $tbl_password);
}
if(($username == $tbl_user) && ($password))
{
if($password)
{
$new_hash = password_hash(('$pwd1'), PASSWORD_BCRYPT);
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Print '<script>alert("Updated, Please relogin.");</script>';
Print '<script>window,location.assign("logout.php");</script>';
}
}
else
{
Print '<script>alert("Incorrect Password");</script>';
Print '<script>window,location.assign("pwd.php");</script>';
}
}
?>
I am able to generate the hash but it is not getting updated in the database and the page is redirected to the given link. I am thinkinging that there is something worng with my
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Any help is appreciated. Thank you.
your code has many syntax errors. i have cited some and put it in comments so you can change it yourself.
<?php
session_start();
if( isset($_SESSION['user']) ){
}
else
{
header("location: index.php");
}
$host = "localhost";
$username = "xxxx";
$password = "xxxxx";
$db_name = "auth_db";
$tbl_name = "users";
$link = new mysqli("$host", "$username" , "$password", "$db_name");
if(mysqli_connect_error())
{
die('Connect Error ('.mysqli_connect_errno().')' .msqli_connect_error());
}
$username = $_SESSION['user'];
$pwd = $_POST['oldpass'];
$pwd1 = $_POST['newpass'];
$pwd2 = $_POST['newpass1'];
if($pwd1 !== $pwd2)
{
Print '<script>alert("New Passwords do not match");</script>';
Print '<script>window.location.assign("pwd.php");</script>';
}
$query = mysqli_query($link, "SELECT * from users WHERE username = '$username'");
$user_exist = mysqli_num_rows($query);
$tbl_user = ""; // instead of reinitializing these as a blank slate just use the unset(); function
$tbl_password = ""; // so its unset($tbl_user); so you can save memory.
$password = 0 ;
if($user_exist > 0)
{
while($row = mysqli_fetch_assoc($query))
{
$tbl_user = $row['username'];
$tbl_password = $row['password'];
$password = password_verify($pwd, $tbl_password);
}
if(($username == $tbl_user) && ($password))
{
if($password)
{
$new_hash = password_hash(('$pwd1'), PASSWORD_BCRYPT);
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Print '<script>alert("Updated, Please relogin.");</script>';
Print '<script>window,location.assign("logout.php");</script>'; //<- window.location.assign();
}
}
else
{
Print '<script>alert("Incorrect Password");</script>';
Print '<script>window,location.assign("pwd.php");</script>'; //<-- window.location.assign();
}
}
?>
Try this
$link = new mysqli($host, $username , $password, $db_name);
mysqli_query($link, "UPDATE $tbl_name SET pasword = ".$new_hash." WHERE username = ".$tbl_user.");

Need help displaying username when user logs in php

So below I have my php code, everything works fine and dandy except when the user logs in and is redirected to the restricted page. When a person signs up, they fill out their first name, email, and password. In the login page it only requires email and password. When they are redirected I want to only display their first name though. I have tried making the session = $result which should return the result of the sql query, but if I do that it doesn't even redirect to the restricted page. What am I doing wrong?
<?php
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = ?;
header ("Location: loggedin/account.php");
}
else {
session_start();
$_SESSION['login'] = '';
}
}
else {
}
}
?>
Here is what I would do.....
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
// Grab user name from db
$row = mysql_fetch_row($result);
if ($num_rows > 0) {
// Add to session variable
session_start();
$_SESSION['login'] = $row['username'];
header ("Location: loggedin/account.php");
}
else {
//Either exit or redirect to login failure page.
}
}
else {
This seems alright to me although I cant test at current.
Edit
You may want to have a read on using the Mysqli and PDO connection, it is slightly quicker and definitely more secure, just a suggestion if you have the time. Also prepared statements would definitely be more secure.
This is how I do Login... You must have an ID for each user in mysql and define
$_SESSION['user_id'] = $fetched_id;
and in loggedin/account.php page you can simply make this:
$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");

How to edit a specific username, password, and email on a database based on what account your logged in with

I would like to have a page in which a user, when logged in, can edit their username/password/email, but am having difficulty in understanding any way in which to do this easily; I am new to PHP and SQL. I know this version of SQL is deprecated, but I am not building this for security, so I am not concerned with SQL injection attacks at the moment.
This is my login code currently.
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "root";
$pass_word = "";
$database = "login";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: Logged.php");
}
else {
echo "<script> alert('Invalid Login')</script>";
}
}
else {
echo "<script> alert('Invalid Login')</script>";
}
mysql_close($db_handle);
}
}
?>
This will then take you to a page called logged.php, which will contain forms for the user to enter in the new username, password, and email they want to use, but I don't know how to make it able to actually edit a database entry and, secondly, to edit the correct entry.
The database columns currently are ID, L1, L2 and Email. What am I doing incorrectly?

Login suddenly stopped working

I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).

Setting session variable from query result

I've been modifying a user authentication system and I'm having trouble setting a session for the admin. The reguser session is setting just fine, but I can't figure out why admin won't set.
A user with a userlevel of 9 is an admin. Yes, I know how to protect against SQL injection. I'm just trying to keep it as simple and easy to read for now. This probably won't get used for anything, I'm just getting some experience with PHP.
Hi everyone, thanks for your help! I got it to work. I had been staring at it for so long that my mind wasn't clear. Took a break from it yesterday, came back to it today and was able to figure it out in less than 5 minutes! You guys are awesome, I love stackoverflow!
function checklogin($email, $pass) {
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(udogoo, $connection) or die(mysql_error());
$pass = md5($pass);
$result = mysql_query("SELECT userid from users WHERE email = '$email' AND password = '$pass'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
$userid = $user_data['userid'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = '$userid'");
$isadmin2 = mysql_fetch_array($isadmin);
$isadmin3 = $isadmin2['userlevel'];
if ($isadmin3 == "9"){
$_SESSION['admin'] = true;
return true;
}
}
else
{
return FALSE;
}
}
You have a return true; if the user data exists. In fact, you only check or admin-ness if the user doesn't exist.
Remove that return true;, as it's not needed there. If you want, add else return false; after the check for the user's existence, and return true; right at the end.
Your logic is flawed as well, here:
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(test, $connection) or die(mysql_error());
$email = mysql_real_escape_string($email);
$pass = md5($pass);
$sql = "SELECT `userid`,`userlevel`
FROM `users`
WHERE `email` = '$email'
AND `password` = '$pass'
LIMIT 1"; //I certainly hope you check email for injection before passing it here. Also want the LIMIT 1 on there because you are only expecting a single return, and you should only get one since `email` should be unique since you're using it as a credential, and this will stop it from looking through all the rows for another match once it finds the one that matches.
$result = mysql_query($sql);
$user_data = mysql_fetch_array($result);
$numrows = mysql_num_rows($result);
if ($numrows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
if($user_data['userlevel'] == 9)
{
$_SESSION['admin'] = true;
}
else
{
$_SESSION['admin'] = false;
}
return true;
}
return false;
}
This should work. No good reason to do two queries when one will do just fine. Returns true if user is logged in, false if user doesn't exist or credentials don't match.
Oops, small syntax error in the SQL statement, corrected. Bigger syntax error also corrected.
And here's how you do the top part in PDO:
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$dbname = 'test';
$dsn = 'mysql:dbname=' . $dbname . ';host=' . $server;
$conn = new PDO($dsn,$user,$password); //Establish connection
$pass = md5($pass);
$sql = "SELECT `userid`,`userlevel`
FROM `users`
WHERE `email` = :email
AND `password` = :pass
LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email',$email,PDO::PARAM_STR,128) //First param gives the placeholder from the query, second is the variable to bind into that place holder, third gives data type, fourth is max length
$stmt->bindParam(':pass',$pass,PDO::PARAM_STR,32) //MD5s should always have a length of 32
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute(); //almost equivalent to mysql_query
$user_data = $stmt->fetch(); //Grab the data
if(is_array($user_data) && count($user_data) == 2) //Check that returned info is an array and that we have both `userid` and `userlevel`
{
//Continue onwards
$userid = $user_data['user_id'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = $userid");
$user_data = mysql_fetch_array($result);
$userlevel = $user_data['userlevel'];
if($userlevel == '9')
{
$_SESSION['admin'] = true;
}
so, your complete code look like this::
<?php
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(test, $connection) or die(mysql_error());
$pass = md5($pass);
$result = mysql_query("SELECT userid from users WHERE email = '$email' AND password = '$pass'");
$user_data = mysql_fetch_array($result);
$numrows = mysql_num_rows($result);
if ($numrows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
//MY ANSWER START HERE
$userid = $_SESSION['userid'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = $userid");
$user_data = mysql_fetch_array($result);
$userlevel = $user_data['userlevel'];
if($userlevel == '9')
{
$_SESSION['admin'] = true;
}
//END HERE
}
else
{
return false;
}
}
?>

Categories