$statement->num_rows returning 0 - php

Im trying do a login system with email confirmation, so when the user confirm the email the value of hash in the database changes from a MD5 value to "confirmed", then in the logon.php I used:
if (isset($_POST['submit']))
{
$confirmed = 'confirmed';
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT id, username FROM users WHERE username = ? AND hash = ? AND password = SHA(?) LIMIT 1";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('sss', $username, $password, $confirmed);
$statement->execute();
$statement->store_result();
if ($statement->num_rows == 1)
{
$statement->bind_result($_SESSION['userid'], $_SESSION['username']);
$statement->fetch();
header ("Location: index.php");
}
else
{
echo "Username/password combination is incorrect.";
}
}
I already tried everything, but the $statement->num_rows always return 0, anybody can help me? Please

I think you are looking for
$statement->rowCount()
I hope that helped

Related

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();

Insert data into Database using php PDO

I'm trying to create a "registration" form using php and mysql. The registration form asks for username and password. If any field is empty, it will let the user know which one. If the username is in use, it will also let the user know.
I know the connection to the database is ok, because I created a user that was I manually added into the database.
The strange thing is that my code is working in Cloud9. But, it wont work on a VM instance installed on google cloud.
In cloud9, it adds the user into the DB. In the google instance, it wont.
Can anyone check this and tell me what I;m doing wrong?
Thanks.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$display = $_POST['display'];
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root",NULL);
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if($stmt->rowCount() == 0 and $username != null and $password != null){
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
echo ("The user ".$username. " has been created.");
Try this, before all u need to check
if username and password is not empty because if username is empty i
cant make query valid to select username
check if username is in use
if username not in use, insert data into database
script
<?php
// error_reporting on
error_reporting(1);
ini_set('error_reporting', E_ALL);
$username = $_POST['username'];
$password = $_POST['password'];
// i commented $display variable because i don't see that u using it anywhere
//$display = $_POST['display'];
// database connection
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","");
// query
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
// check if username and password is not empty
if ($username != '' && $password != '')
{
// check if username is in use
if($stmt->rowCount() > 1)
{
echo "Username in use, please choose another one.";
}
else
{
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
// if last inserted id is true
if ($dbh->lastInsertId())
{
echo "The user ".$username. " has been created.";
}
else
{
echo "User not registered, please try again.";
}
}
}
else
{
echo "Please enter username and password.";
}
?>

How can I fetch a row in mysql oop

I am making a change password function. Currently It is just changing the password. But I want to amend it a bit. If email and password is valid then it should change the password, otherwise not. This is my code. Can anyone help me?
function CHANGE_PASSWORD($conn, $MSG)
{
$sql = $conn->prepare("UPDATE users SET password = ? WHERE email = ? AND password=?");
$sql->bind_param("sss", $newpass, $email, $password);
$email = $_REQUEST["EMAIL"];
$pass = $_REQUEST["PASSWORD"];
$newpass = $_REQUEST["NEW_PASSWORD"];
if ($sql->execute()) {
if($sql->affected_rows == 0) {
$json["STATUS"] = "FAIL";
$json["MESSAGE"] = "Invalid email / password";
} else {
$json["STATUS"] = "SUCCESS";
$json["MESSAGE"] = "Password Update Successful";
}
} else {
$json["STATUS"] = "ERROR";
$json["MESSAGE"] = "Please try again later.";
$json["ERROR"] = $sql->error_list;
}
$sql->close();
return json_encode($json);
#function ends
}
My Current URL looks like this
http://localhost/safespaces/server.php?REQUEST=CHANGE_PASSWORD&EMAIL=mr.aleem001%40gmail.com&PASSWORD=haioye&NEW_PASSWORD=12345
To fetch a row, use
$result = $sql->get_result();
$row = $result->fetch_assoc();
I Hope it Helps

Having trouble with PDO queries

Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}

After selecting all from a certain row, is there a way to grab data from certain columns not defined?

So my SELECT statement is selecting all from a row in the users table. There is a column in that row labeled "user_level" and I want to use the data from that column to differentiate between an admin and a guest. Is there a way to use "user_level" (and maybe bind it to a session variable) without me having to write another SELECT statement?
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = :name and
user_password = :password");
$query->bindValue(":name", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false details
$error = 'Incorrect details!';
}
}
}
You don't need no rowCount here.
as well as half of the duplicated and triplicated code.
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT user_level FROM users WHERE user_name = ? and user_password = ?";
$stm = $pdo->prepare($sql);
$srm->execute(array($username,$password));
$level = $stm->fetchColumn();
if ($level !== FALSE) {
//user entered correct details
$_SESSION['user_level'] = $level;
header('Location: index.php');
exit();
}
}
$error = 'Incorrect details!';

Categories