getting undesired result by prepare statement mysqli php - php

Hi, I am new to PHP and I am trying to write prepare statement for login but as given below code my query is not getting any row but getting field_count.
And if I put that
SELECT * FROM users WHERE UserName = 'DemoUser'
in direct database I am getting one row but here $stmt->num_rows is zero. What am I missing.
// in connections.php
$dbh = new mysqli($host, $username, $password, $database);
include('connections.php');
include('config.php');
include('comman_functions.php');
if(isset($_POST['password']) && $_POST['password']!=''
&& isset($_POST['username']) && $_POST['username']!=''
&& isset($_POST['location']) && $_POST['location']!='') {
$username = "DemoUser";
$stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
$stmt->bind_param("s", $username);
$stmt->execute();
error_log($stmt->num_rows);
if($stmt->num_rows>0){
$row = $stmt->fetch();
error_log("logged in!!!");
$stmt->close();
} else {
$_SESSION['error'] = 'Invalid Username or Password';
header('Location:index.php');
}
} else {
$_SESSION['error'] = 'Please provide Username and Password';
header('Location:index.php');
}

Try THis!
U need to add $stmt->bind_result(); after $stmt->execute();
$dbh = new mysqli($host, $username, $password, $database);// in connections.php
<?php
include('connections.php');
include('config.php');
include('comman_functions.php');
if(isset($_POST['password']) && $_POST['password']!='' && isset($_POST['username']) && $_POST['username']!='' && isset($_POST['location']) && $_POST['location']!=''){
$username = "DemoUser";
$stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result();
error_log($stmt->num_rows);
if($stmt->num_rows>0){
$row = $stmt->fetch();
error_log("logged in!!!");
$stmt->close();
}else{
$_SESSION['error'] = 'Invalid Username or Password';
header('Location:index.php');
}
}else{
$_SESSION['error'] = 'Please provide Username and Password';
header('Location:index.php');
}
?>

If you have problems making work this num_rows, you have to declare ->store_result() first.
<?php
$mysqli = new mysqli("localhost","root", "", "tables");
$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();
$rows = $query->num_rows;
echo $rows;

Related

prepared statements in if else statement

Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();

Login user using password_verify

I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();

Getting a value from sql table for a certain user using sessions

How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.

Error login script mysqli

I have this login code:
$con = new mysqli($host, $user, $password, $database);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, password FROM user WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
$result=$con->query($stmt);
$row=$result->fetch_array(MYSQLI_ASSOC);
$status = $row['status'];
if($status=='d') {
echo "YOUR account has been DEACTIVATED.";
} else {
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();
and when press login buton is show me this errors:
Warning: mysqli::query() expects parameter 1 to be string, object given in /nginx/html/user/demo/login.php on line 93
Fatal error: Call to a member function fetch_array() on a non-object in /nginx/html/user/demo/login.php on line 94
There is lines with this errors:
line 93 is: $result=$con->query($stmt);
line 94 is $row=$result->fetch_array(MYSQLI_ASSOC);
When you're using prepared statements, you don't call query or fetch_array. You call fetch, and it puts the results in the variables that you bound with bind_result.
You were also referencing values that you weren't listing in the SELECT clause.
$con = new mysqli($host, $user, $password, $database);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, status, user_id FROM user WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $status, $user_id);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
$stmt->fetch();
if($status=='d'){
echo "YOUR account has been DEACTIVATED.";
}else{
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();

PHP MYSQLI prepared statements login and check the user status

I am learning to make website with some video tutorials based on mysqli. I came to know that using prepared statements are more secure and I am trying to create a login system. Here is what I have done so far.
This code helps me login success fully.
<form action ="" method="post">
User Name:<br/>
<input type='text' name='username' />
<br/><br/>
Password:<br/>
<input type='password' name='password' />
<br/><br/>
<input type='submit' name='submit' value='login'>
</form>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{$_SESSION['Logged'] = 1;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();
?>
But I also need to check if the user have not activated or have been banned or deactivated. So I made another code.
And here is the code I made
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
$result=$con->query($stmt);
$row=$result->fetch_array(MYSQLI_ASSOC);
$user_id= $row['user_id'];
$status = $row['status'];
if($status=='d'){
echo "YOUR account has been DEACTIVATED.";
}else{
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->free_result();
$stmt->close();
}
else
{
}
$con->close();
?>
When I use this I get the following errors
Warning: mysqli::query() expects parameter 1 to be string, object given in F:\XAMPP\htdocs\login\login.php on line 33
Fatal error: Call to a member function fetch_array() on a non-object in F:\XAMPP\htdocs\login\login.php on line 34
I have database table columns
user_id,
username,
password (md5),
user_level,
status.
Under user_level I have the following
a = admin
m = member
Under status
a = activated
n = not activated
d = deactivated
b = banned
While logging in I need to check if the user status and if it is activated it should move to index page or if it is d it should show the user has been deactivated and likewise for others.
How to do it in prepared statements?
And I have this connect.php in all page
?php
//error_reporting(0);
'session_start';
$con = new mysqli('localhost', 'username', 'password', 'database');
if($con->connect_errno > 0){
die('Sorry, We\'re experiencing some connection problems.');
}
?>
I think you need to take a look into how mysqli_ works. This should get you in the right direction.
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$user_id = 0;
$status = ""
$stmt = $con->prepare("SELECT user_id, username, password, status FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($user_id, $username, $password, $status);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
if($stmt->fetch()) //fetching the contents of the row
{
if ($status == 'd') {
echo "YOUR account has been DEACTIVATED.";
exit();
} else {
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();

Categories