how i can use the PDO results? - php

Hello every one i'm trying to do a login method for my website, and i'm having a small problem. I'm getting the data from PDO connection but every time im checking the password it returns false. is my variables wrong?
here is my sql query
$this->result = $this->sql->prepare('SELECT username,password FROM User WHERE username=:username AND password=:password');
$this->result->bindParam(':username', $username, PDO::PARAM_STR);
$this->result->bindParam(':password', $password, PDO::PARAM_STR);
$this->result->execute();
and here is my if statement:
$this->result=$this->result->fetch(PDO::FETCH_OBJ);
if (($password == $this->result->password) && ($username == $this->result->username)){
i'm not getting error it just return always false. i'm not encrypting the password yet so is not this problem. i think $this->result->password is the problem. can anyone correct me please?
thank you

You can use this as well:
$username=$_GET['username'];$password = $_GET['password'];/*of $_POST, depending of which you used*/
$this->result = $this->sql->prepare('SELECT username,password FROM User WHERE username='$username' AND password='$password');
$this->result->execute();
And then use fetchAll like this:
$this->results = $this->result->fetchAll(PDO::FETCH_ASSOC);
if($this->results['username']==$this->username && $this->results['password']==$this->password){/*u had beed loged in*/}

Your logic should work. Most likely, the SQL is not returning anything. Try printing out the result of your fetch.
$this->result=$this->result->fetch(PDO::FETCH_OBJ);
print_r($this->result);
Also, if you are checking for username and password in the SQL query, you don't have to check it again in the if statement. With the SQL statement you are using, you should be able to just check if it returned a row or not to validate the user.
$numrows = $this->result->rowCount();
if ($numrows == 1) {
// User is valid
}
else {
// User is not valid
}

Related

PHP PDO array result returning but not working with IF

I have a PHP script using PDO where I check a user's submitted email/password against a database. If the query returns a row, it is supposed to take the user to a success page, or if the credentials are incorrect they are supposed to be taken to a failed login page. However, the user is always taken to the fail page.
$sql = "SELECT email, password FROM user WHERE email= $email AND password = $password";
$stm = $db->prepare($sql);
$stm->execute();
$result = $stm->fetchColumn();
if ($result !== FALSE) {
header('Location: ./success.html');
}
else {
header('Location: ./failed.html');
}
Your original problem was simply missing quotes around the variables inserted into the query.
Just fixing that problem would leave you vulnerable to SQL injection attacks. Making proper use of statement preparation and execution will solve that problem. And never, never, store plaintext passwords. When you save them, use password_hash and then use code like this to verify them.
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "SELECT password FROM user WHERE email= ?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$result = $stm->fetchColumn();
if ($result !== FALSE) {
if (password_verify($password, $result[0])) {
header("Location: ./success.html);
exit;
}
}
header("Location: ./failed.html");
More details on password hashing can be found elsewhere on SO.
And please note that for brevity I'm not checking the result of the prepare() or execute() functions. You should be doing this.

Why is my sql prepared statement not giving correct responses?

I'm trying to create a login account system for my website and when a user registers, I check if there is already an account in the database. I created a function called 'check_user_exists' and here is the code for that
function check_account_exists($username, $conn){
if($stmt = $conn->prepare("SELECT * FROM users WHERE username=?")){
$stmt->bind_param('s', $username);
$stmt->execute();
echo $stmt->num_rows;
if($stmt->num_rows == 1){
return true;
}else{
return false;
}
}else{
//couldn't prepare statement
return false;
}
}
However when I go run this it returns false every time even when I know that a value in the database already exists. I haven't had any MySQL errors before this but I checked the error log and it doesn't show any errors. I added echo stmt->num_rows; but it always outputs 0. What is the matter?
Ok turns out I need to use $stmt->store_result(); after $stmt->execute(); That was preventing correct responses.

PHP/MySQL - Checking results

I'm trying to create a login system with PHP, but the SQL query is not returning the result I'm expecting.
I have a typical username and password page, and I'm using what the user types in there to check for an account. I know for a fact that the database contains real usernames and passwords but the call to mysqli_num_rows is always returning 0.
Is there something I'm doing wrong?
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con, "SELECT * FROM StaffTable WHERE staffNo='$username' AND password='$password'");
echo mysqli_num_rows($result); //This always prints out 0.
if(mysqli_num_rows($result) == 1)
{
echo "OK";
}
Ignoring the plain-text-password thing which you claim to be aware of, something like this perhaps...
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
$stmt = $con->prepare('SELECT 1 FROM StaffTable WHERE staffNo = ? AND password = ?');
if (!$stmt) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('ss', $username, $password);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
if ($stmt->fetch()) {
echo 'OK';
}
To summarise...
I've checked that the input variables are set and assigned defaults if they're not that shouldn't produce any false positives
I've used a prepared statement with bound parameters to avoid SQL injection vulnerabilities
I throw exceptions when errors occur. These are great because they halt execution and give you all the information you need to debug the problem.
This is my main problem with mysqli over PDO. mysqli is simply not noisy enough when errors occur. You shouldn't have to manually check for error conditions all the time.
I've changed the query to a simple boolean check as that's all you were using it for. The row either exists, or it doesn't.
Try something more along the lines of
$username=$_POST['username'];
$password=md5($_POST['password']);
$query="SELECT * FROM StaffTable WHERE staffNo='".$username."' AND password='".$password."'";
$result=mysqli_query($con,$query);
if (mysqli_num_rows($result)==0)
{
echo "Incorrect Password Or Username Combo";
}
else {
while($row=mysqli_fetch_object($result)) {
$_SESSION['id']=$row['id'];
}
I would say to start with at least running the passwords in encryption for now and look into SQL injection and upgrade as you learn more about what you're looking at.
The biggest flaw in yours aside from what's already been pointed out is
($con, "SELECT * FROM StaffTable WHERE staffNo='$username' AND password='$password'");
With the variables you cannot put them within the query that way; you would want to do something more along the lines of
($con, "SELECT * FROM StaffTable WHERE staffNo='".$username."' AND password='".$password."'");
If you'll notice I escaped from the plain text so that the variables would be set. The reason you're returning 0 results everytime is because you are actually searching for username $username with $password as their password.
Good luck!

PHP username validation against MySQL

Plenty of time, spent, here is where I'm at:
$uname_query = mysql_query("SELECT username FROM blog_members WHERE username='".$username."'");
if ($uname_query == $username) {
$error[] = 'Username is already taken';
}
I'm trying to use the SQL query $uname_query to pull the $username entered in a form, if it exists, then use an if statement to display the error, if it exists.
As it is coded right now, I get no error but also no functionality.
What am I missing?
You need to use a fetch.
$row = mysql_fetch_row($uname_query);
// $row[0] will contain the first column of the first row (username)
if ($row[0] == $username) { }
However, you should look at using PDO or MySQLi since the MySQL api is deprecated. You should also use prepared statements if $username is provided by the user.
In PDO you could do:
$stmt = $pdo->prepare("SELECT username FROM blog_members WHERE username=?");
$stmt->execute(array($username));
// fetchColumn will return the first column of the first row (username)
if ($stmt->fetchColumn() == $username) { }
This protects against SQL injections by providing a prepared statement without $username and binding it in the execute() function. PDO requires some different setup initially too, but here is a good tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
You have to fetch the data before compare as
$row = mysql_fetch_array( $uname_query);
if($row["username"] == $username){
$error[] = 'Username is already taken';
}
You need to fetch the data from the query first.
$uname_query = mysql_query("SELECT username FROM blog_members WHERE username='".$username."'");
$arr=mysql_fetch_array($uname_query);
if ($arr["username"] == $username) {
$error[] = 'Username is already taken';
}
For one, you need to fetch it. Use mysql_fetch_row(). Secondly, I'm not sure what that $error[]='string' business is. Are you trying to use an array?
Although I suggest moving to mysqli since mysql is deprecated. Also, I hope you sanitized that string well.

Need help regarding a PHP/SQL login function

Before you say it: I know the passwords should be encrypted/hashed, but I want to get this down first:
I have this login function and a SQL database. However, the login function doesn't seem to work and I haven't the faintest idea why. I am probably missing something stupid, but have been struggling with this for a while now. Any help would be appreciated!
NOTE: the file db_connect.php is really just a basic connecting to the database, nothing wrong there
FUNCTION.PHP:
<?
function login($username, $password, $con)
{
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
$result = mysqli_query($con, $myQuery);
if (mysql_num_rows($result) == 0)
{
return false;
}
else
{
return true;
}
}
?>
PROCESS-LOGIN.PHP:
<?php
include 'db_connect.php';
include 'functions.php';
if (isset($_POST['username'], $_POST['pword'])) {
$username = $_POST['username'];
$password = $_POST['pword']; // The hashed password.
if (login($username, $password) == true) {
// Login success
header('Location: welcome.html');
}
else
{
// Login failed
header('Location: index.html');
}
}
else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
You are not providing the $con parameter to login function.
function login($username, $password, $con)
You are calling it as
login($username, $password)
Try providing the connection argument to see if it works.
Also note the answer kingkero made. You are using functions from different libraries.
Some things I noticed
Are you using method="POST" in your form?
Your SQL query is vulnerable to SQL injections
your mixing mysql_* with mysqli_* functions
missing $con parameter for login function
You are mixing MySQLi (mysqli_query) with MySQL (mysql_num_rows) - decide for either one (preferably the former).
If you are using MySQL, the parameters for mysql_query are in wrong order.
In addition to that you are failing to pass the connection to the login as a parameter (as WoLfulus mentioned).
Some additional info as you seem to be learning:
The return statement of login can be simplified to return mysql_num_rows($result) == 1;. This will return TRUE if one record was found and FALSE otherwise - no need for an if/else statement here, you already have the logic you need.
Right now anyone can access welcome.html without logging in by simply typing the address in the browser. This can be avoided by using sessions.
Since you don't properly escape the user input (which one should never trust!), you are vulnerable to SQL injections. mysql_real_escape_string is a start but no 100% solution. If you used prepared statements on the other hand, you wouldn't need to worry.
I'm answering since I don't have enough reputation to comment your question.. But you should keep your variables outside the quotes and add mysql_real_escape_string() to prevent mysql injection..
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
Should be:
$myQuery = "SELECT * FROM Members WHERE Username = '". mysql_real_escape_string($username) ."' and Password = '". mysql_real_escape_string($password) ."';";

Categories