How to debug "query not executed" error in MySQLi? - php

Please can someone help me in guiding me in the correct direction to get this code to work. I have migrated from PHP5.4 to PHP5.5 and I wonder if that might be the reason for the difficulty?
function auth($username, $password) {
// hash password using md5 encryption
$hash_pass = md5($password);
// prepare SQL query
$username = mysqli_real_escape_string($username);
$query = "SELECT * FROM `area51_users` WHERE `user_name`='".$username."'";
if ($result = mysqli_query($Connection, $query) or die (mysqli_error()." (query not executed)")) {
if (mysqli_num_rows ($Connection, $result) > 0) {
// record exits
if ($row = mysqli_fetch_assoc($result) or die (mysqli_error())) {
if ($hash_pass == $row['user_password']) {
// password is valid
// setup sesson
session_start();
$_SESSION['username'] = $username;
$_SESSION['CMS_AUTH'] = "YES";
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
}
Currently I am getting the error "query not executed" from the first if statement.
I am new to PHP and trying to work this all out.

The problem is the scope of $connection (it's not available in your function)
-> Check php variable scope http://php.net/manual/en/language.variables.scope.php
Second your code has many unnecessary things.
You need no if/else or return false, when you use die.
Instead of die you should use Exceptions!
Cleaned up code:
function auth($username, $password)
{
//you need this variable!!!
global $Connection;
// hash password using md5 encryption
$hash_pass = md5($password);
// prepare SQL query
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$query = "
SELECT
*
FROM `area51_users`
WHERE
`user_name`= '" . $username . "'
AND `user_password` = '" . $password . "'
";
if ($result = mysqli_query($Connection, $query)) {
if (mysqli_num_rows($Connection, $result) > 0) {
// record exits
if ($row = mysqli_fetch_assoc($result))) {
// setup sesson
session_start();
$_SESSION['username'] = $username;
$_SESSION['CMS_AUTH'] = "YES";
return true;
}
}
}
echo mysqli_error($Connection);
return false;
}
You could also enhance your query with prepared statements (safer)
How can I prevent SQL injection in PHP?

Related

My php function will not be called

I have the following code to connect between mysql database and android.
$conn = mysqli_connect($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn) {
$response["Connection"] = 1;
}
else {
$response["Connection"] = 0;
}
$userID= $_POST['user_id'];
function recordExists() {
$query = "SELECT * FROM user_table";
$result = mysqli_query($conn, $query);
$response["found"] = "i am here";
while($row=mysqli_fetch_array($result)){
$response["found"] = $row['user_id'];
if($row['user_id']==$userID){
return true;
}
}
return false;
// $result_num_rows = mysqli_num_rows($result);
//
// if($result_num_rows>0) {
// return true; // The record(s) do exist
// }
// return false; // No record found
}
$exists=recordExists();
if ($exists) {
$query = "SELECT * FROM user_table WHERE $userID";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array ($result);
$Nickname = array();
if ($row['nickname'] == NULL){
array_push($response["nickname"], "False");
}else{
array_push($response["nickname"], $row["nickname"]);
}
$response["Sync"] = "Already Added";
echo (json_encode($response));
} else {
$UserToBeAdded= $_POST['user_id'];
$NameToBeAdded= $_POST['name'];
$EmailToBeAdded= $_POST['email'];
$UserToBeAdded2 = mysqli_real_escape_string($conn, $UserToBeAdded);
$NameToBeAdded2 = mysqli_real_escape_string($conn, $NameToBeAdded);
$EmailToBeAdded2 = mysqli_real_escape_string($conn, $EmailToBeAdded);
$sql_query = "insert into user_table (user_id, name, email) values ('$UserToBeAdded2', '$NameToBeAdded2', '$EmailToBeAdded2');";
mysqli_query($conn, $sql_query);
$response["ID"] = $UserToBeAdded2;
$response["Name"] = $NameToBeAdded2;
$response["Email"] = $EmailToBeAdded2;
$response["Sync"] = "Just Added";
$response["nickname"] = "False";
echo (json_encode($response));
}
mysqli_close($conn);
from the above code, i can receive responses from the php side. however the following response is not received.
$response["found"] = "i am here";
if u see from my code above, basically the function recordExists() will definitely be called. however the response " i am here" is not encoded in JSON when i emulate the android app. anything wrong?
try to declare the response variable above all functions. so add $response=array();on top of the file.
here you can read up about the scope of php variables:
https://secure.php.net/manual/en/language.variables.scope.php
You have a variable scope issue with the connection variable. Pass the connection variable as a parameter.
recordExists($conn);
Also use prepared statements to prevent sql injection attacks.

returning values from within functions

I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}

If and else statement , test on the user account status

I want to make test on the status of the user account.
If the account is active I redirect him to the user page
If the account is not active I redirect him to login page again with an error
Here’s my code
<?php
require('conexion.php');
$username = '';
$password = '';
if (isset($_POST['username']) || !empty($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']) || !empty($_POST['password']))
$password = $_POST['password'];
$q1 = "select * from user where username='" . $username . "' and password='" . $password . "' ";
$r1 = $db->query($q1);
$i = 0;
echo $q1;
while ($d1 = $r1->fetch()) {
$i++;
//$id_perso = $d1['id_perso'];
$type = $d1['type'];
$nom = $d1['nom'];
$prenom = $d1['prenom'];
$statut = $d1['statut'];
$user_id = $d1['id_user'];
}
if ($i == 1) { // START IF
session_start ();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if ($statut = 'actif') {
if ($_SESSION['type'] == 'admin') {
$path = "admin/index.php";
}
if ($_SESSION['type'] == 'professeur') {
$path = "professeur/index.php";
}
if ($_SESSION['type'] == 'doctorant') {
$path = "doctorant/index.php";
}
header("Location:".$path);
} elseif ($statut = 'inactif') {
header("location:login.php?inactif");
}
} else {
header("location:login.php?error=1");
}
?>
Why don't you use a boolean, should be easier.
/*
1. Get Status from Database
2. When the user is active, you set the boolean true, else false. */
$booleanVar = false;
if($booleanVar) {
// user is active
} else {
// user is inactive
}
EDIT:
Redirecting with header works like this, I believe its Case Insensitive:
header('Location: somesite.php?abc');
Also you have to check values with "==" (for equal) or "===" (for identical)
You could simply get the same result if you do this with a simple query:
You check if the password and the username matches AND check if the account has been activated.
$sql = 'SELECT `id` FROM `user` WHERE `username` = '$username' AND `password` = '$password' AND `statut` = 1'
You then can run the query and check if number of rows is greater than 0.
$sql = $db->query($sql);
$results = $sql->fetch();
if (count($results) > 0) {
// Account is activated
} else {
header("location: login.php");
exit;
}
You are also vulnerable to SQL-injections by inserting your variables directly into your query, wich Edhurtig noticed! The best way to prevend SQL-injections is to use PDO prepared statements.
First and foremost: DO NOT STORE PASSWORDS IN PLAINTEXT. Do some research into secure hashing algorithms (not md5) or use a third party authentication service like Google, Facebook, Github, ect.
Second: This code is vulnerable to SQL injection via $_POST['username'] and $_POST['password']
Also it was a bit unclear what was being asked but I felt it was important to point out the aforementioned issues because they are so security critical.
Here is what I was able to cleanup. I would strongly recommend using a third party authentication service though
<?php
require('conexion.php');
$salt = "random_string";
$username='';
$password='';
if (isset($_POST['username'])||!empty($_POST['username'])) $username = $_POST['username'];
if (isset($_POST['password'])||!empty($_POST['password'])) $password = $_POST['password'];
$hashed_password = some_hashing_function_1000_times($password, $salt);
$q1="SELECT * FROM user WHERE `user`.`username` = '%s' AND `user`.`password` = '%s' LIMIT 1";
// I hope that $db has a prepare function, it prevents SQL injections from $_POST['username'] and $_POST['password']
$sql = $db->prepare($q1, $username, $hashed_password);
$r1= $db->query($q1);
$user = $r1->fetch();
if( $user ) { // START IF
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if($statut == 'actif'){
if($_SESSION['type']=='admin') { $path="admin/index.php"; }
if($_SESSION['type']=='professeur'){ $path="professeur/index.php"; }
if($_SESSION['type']=='doctorant') { $path="doctorant/index.php"; }
header("Location: " . $path);
exit();
}
else if ($statut == 'inactif') {
header("Location: login.php?inactif");
exit();
}
}
header("Location: login.php?error=1");
exit();
// No Closing PHP tag at end of file

Prepared statement for login function PHP

I am trying to write a parametrised login function in PHP.
The function should get the $id and $pass bind and execute statement and return an associative array from the database with $id, $password, $user_first_name.
Checking for user id and password validation, if true the session should start and set the session with the username from the database.
For some reason I can't get this working. Any suggestions?
Thanks!
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT user_id, user_name, user_password FROM Users WHERE user_id = ? ");
$stms->bind_param('i', $user_id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbuser_id = $row['user_id'];
$dbpassword = $row['user_password'];
$dbuser_first_name = $row['user_first_name'];
}
if($id == $dbuser_id and $password == $dbpassword)
{
session_start();
$_SESSION['session_user_first_name'] = $dbuser_first_name;
}
else
{
session_unset();
echo "Credentials do not match";
}
}
}
You have
$stms->bind_param('i', $user_id);
But your function signature is:
public function logIn($id, $password)
So you probably want:
$stms->bind_param('i', $id);
Have a look at $stms->bind_param('i', $user_id);:
stms should be stmt
$user_id should be $id
...

PHP PDO Logging Into Account

<?php
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
$rowcount = $query->rowCount();
if($rowcount == 1){
$row = mysql_fetch_array($query);
$dbPass = $row["password"];
if($password == $dbPass){
session_start();
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else
return false;
} else
return false;
}
?>
This is a PHP code snippet from a project I am globally converting to PDO. This is the functions.php file for the login page. Obviously it is not fully converted to PDO so don't criticize that, but basically in the login.php file I have it access this method, and pass the database(which is required in), the username, and the password from the form. I setup a basic query to find all users with the username input of the form. Then i prepare, and execute the query. I then need a row count, so I setup a $rowcount variable running the rowCount() method on the query, but the code does not move past there. The rowcount is == 0 when I echo it out so it won't proceed to the following if statement. Am I doing something wrong with the PDO or something? Or the rowCount(). My suspicion is that perhaps I am calling the rowCount() too late, so I tried moving it up before I execute the $query but no luck. Thank you!
___EDIT___
<?php
session_start();
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
if($query->rowCount()){
$row = $query->fetch();
echo $row;
$dbPass = $row["password"];
if($password == $dbPass){
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
Don't mix pdo and mysql_ functions together. NEVER!
Don't store password in plain text. NEVER! Instead try Password_compat !
First:
Is to replace
$row = mysql_fetch_array($query);
with
$query->fetchAll(PDO::FETCH_ASSOC)
Second:
session_start() should appear at the top of your script, not inside your function.
Third:
Is to replace
$rowcount = $query->rowCount();
if($rowcount == 1){
//
}
with this:
if($query->rowCount()){}
Fourth:
This is BAD!!
return true;
} else
return false;
} else
return false;
}
Always, use a complete delimiter. You are instilling a bad-codding practice, that will haunt you for life.
Simple do
if($foo){
if(){
//do something
}else if{
//do something
}else{
//do something
}
}
Fifth:
~Not good, but definitely better that your approach.
function small_query(pdo $pdo, $query, array $value){
$stmt = $pdo->prepare($query);
$stmt->execute($value);
return $stmt->fetchAll();
}
$pdo = new PDO('mysql:host=localhost; dbname=foo', 'root', 'pass');
$result = small_query($pdo, "SELECT * FROM users WHERE name = ?", array($_POST['name']))
EDIT.
Since you seem to love your code so much, I have done it your way. Try this:
<?php
session_start();
function login($database, $username, $password){
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $database->prepare($query);
$stmt->execute(array($username));
if($stmt->rowCount()){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION["id"] = $result["id"];
$_SESSION["username"] = $result["username"];
$_SESSION["email"] = $result["email"];
return true;
}else{
return false;
}
}

Categories