Check if user exists in database error - php

I'm really new to php and been following a tutorial on youtube by php academy. Basically it's a script(s) that allows for login,registering and a remember me option, the tutorial is 2 years old so I tried to change some of the mysql functions to mysqli but I'm running into some problems..when I enter a username and hit login I get a "mysql_num_rows() expects parameter 1 to be resource, string given in user.php line 9" error and my if statement says "cannot find username try registering" but it should show "exists" because the username I entered is in fact in the database..I'm puzzled, also please forgive me if the script isn't the most secure, I know things should be escaped and such, your help would be appreciated
User.php :
<?php
function user_exists($username)
{
$username=$username;
$query = ("SELECT count(`user_id`) FROM `users` WHERE `username`='$username'");
if(mysql_num_rows($query)===1)
{return true;
} else{
return false;
}
}
?>
login.php
<?php
include ('core/init.php');
if(user_exists('drellen')===true){
echo "exists";
}
if(empty($_POST)===false){
$username=$_POST['username'];
$password=$_POST['password'];
if(empty($username) === true|| empty($password)=== true)
{
echo $error[]="Enter a username and password";
}
else if (user_exists($username)===false)
{
echo $error[]="Cannot find username try registering";
}
}
please note that the init.php has users.php included in it*****
Might have a mixture of the old mysql and the new mysqli functions mixed in, help making it full mysqli would be appreciated

You have not used mysql_query() to run query. How you get number of rows without it.
Note -> You should use mysqli_* functions instead of mysql_*
$query = mysqli_query("SELECT count(`user_id`) FROM `users` WHERE `username`='$username'");
//$row = mysqli_fetch_array($query);
$count = mysqli_num_rows($query);

you can try this
function user_exists($username)
{
$result = mysql_query("SELECT `user_id` FROM `users` WHERE `username`='$username' LIMIT 1 ") or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}
Note : mysql_* is deprecated. use mysqli_* or PDO
UPDATE 2:
function user_exists($username)
{
global $your_db_conn;
$sql = "SELECT `user_id` FROM `users` WHERE `username`='$username' LIMIT 1 ";
$result = mysql_query($sql, $your_db_conn) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}

Here is a working example
After doing some digging around i found that the most important part in this new function is calling the global $db, and for sanitizing adding the $db, $data as well as in the query. if you look up other basic exampels of using mysqli_query($db, $sql); you will catch onto this quite easily
<?php
$db = mysqli_connect('localhost', 'root', 'password', 'database');
function sanitize($data) {
global $db;
return mysqli_real_escape_string($db, $data);
}
function user_exists($username)
{
global $db;
$username = sanitize($username);
$sql = "SELECT `id` FROM `Users` WHERE `username`='$username' LIMIT 1";
$result = mysqli_query($db, $sql) or die('query');
if($row = mysqli_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}
?>
<h1>test</h1>
<?php
if (user_exists('admin') === true){
echo "Good news, this exists";
} else {
echo "no good";
}
?>

Related

MySQL stored functions don't seem to work in PHP

I have to develop a administrative system at my work (we usually don't do that, but one client have a very specific need, so we skipped from WordPress to pure PHP, MySQL and HTML5), I'm using PHP and MySQL, but i can't get the stored functions on MySQL working in PHP, I had tested it in phpMyAdmin and it works fine.
All I'm trying to do right now is a login webpage.
My code:
require 'connect.php';
function query($query) {
$connection = connect_db();
$result = mysqli_query($connection,$query);
return $result;
}
function validateUser($email, $password) {
$connection = connect_db();
$query = "SELECT email, password FROM usuario WHERE email =". $email ."AND password =" . $password ."";
$result = mysqli_query($connection,$query);
return $result;
}
function login($email, $password) {
$validate = validateUser($email,$password);
if($validate == 1) {
session_start();
//NOT IMPORTANT
header('Location:http://www.google.com/');
}
} else {
echo 'error';
}
}

PHP: else condition is not working in php

I have designed a admin login page. The if condition is working but else condition is not. After putting wrong username or password it shows blank on the same page.
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count == 1)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
You used mysql_error(); which is causing the error of blank page.
Use the below code will fix your problem.
$sql = mysqli_query($DBCONNECT,$query);
$count = mysqli_num_rows($sql);
Remove or die(mysqli_error($link)) from your code that will work fine for you.
Note: mysqli_num_rows can be used for Procedural style only not for object oriented style.
Can you try with this code? Difference is putting if($count) instead of if($count==1)
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
Mysqli Also make result as object so you can do this :
$sql = mysqli_query($con, "SELECT * FROM users WHERE userid='$userid' and pass='$pass'") or die(mysqli_error());
your mysqli_error only will show if statement wrong and i don't think you will put wrong statement but good in development.
then you can check if statement works by if and put this :
echo $sql->num_rows;
can put in variable :
$count = mysqli_num_rows($sql) to $count = $sql->num_rows
or
if($sql->num_rows == 0) {
// here your blank result for error
} else {
// show result here.
}
Link : Check PHP Site Mysqli Num Rows Result

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

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?

mysql_result to mysqli issue

ive tried in vain for a good amount of time to convert this string from mysql to mysqli with no luck. here is what i had for mysql :
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
ive tried:
function user_exists($username) {
$link = mysqli_connect("localhost", "username", "password", "table");
$username = sanitize($username);
$usernamequery = "SELECT COUNT(`userid`) FROM `table` WHERE `username` = '$username' ";
$query = mysqli_query($link, $usernamequery);
$queryarray = mysqli_fetch_array($query, MYSQLI_BOTH);
$queryarrayres = mysqli_num_rows($query) ;
if ($queryarrayres > 0) { true; } else { false;}
}
numerous hits of this issue on here from previous users but none of them seem to work for me.this and this for example. it all seems fine until i get to converting the mysql_result query and it goes to pieces. i understand that mysql_result in the above situation is essentially checking to see if theres one row selected and thats it equal to one, ie present, but i just cant seem to get something equivalent in the mysqli.
function login($username, $password) {
$link = mysqli_connect("localhost", "username", "pw", "db");
$username = sanitize($username);
$password = md5($password);
$loginquery = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = $username AND `password` = $password";
$query = mysqli_query($link, $loginquery);
$queryarray = mysqli_fetch_array($query);
$queryarrayres = $queryarray[0];
return ($queryarrayres > 0)? $userid :false;
}
in this instance, $queryarrayres prints as 1 at the right occasion, and zero the rest. so that bit works. the function actually contains a password element too, which ive added.
unfortunately when i use the function is continually returns false. i have tested on a test page, and if i change $username and $password to absolute variable its seems to work. the code is identical between the old version (not shown), and this version, aside from the obvious mysqli updates. this narrows the issue down to three possibilities. 1) something to do with $username and $password population. 2) the $usernamequery string. 3) the return of the function. i reckon its three given that no other code has changed, but i cant put my finger on whats going on here.
Use this function below, it works
function user_id_from_username ($username){
global $connect;
$username = sanitize($username);
$query = " SELECT user_id FROM users WHERE username = '$username' ";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo $row["user_id"];
}
Your new user_exists function is not returning anything.
change
if ($queryarrayres > 0) { true; } else { false;}
to
return ($queryarrayres > 0)?true:false;
You may use the following function and call the function
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}

How to successfully rewrite old mysql-php code with deprecated mysql_* functions? Part II

Continuing from this topic where we explained most problems with PDO How to successfully rewrite old mysql-php code with deprecated mysql_* functions? now about understanding prepared statements... So in order to get remove mysql_* strings there are some examples so my question for all and other users may this find helpfull which solution is the best ... so example of old "made up* code:
in config.php:
$db = new dbConn('127.0.0.1', 'root', 'pass', 'people', 'login');
in login.php
$db->selectDb("login");
$query = mysql_query("SELECT * FROM account WHERE id='".$_session["id"]."' LIMIT 1");
$result = mysql_fetch_array($query);
$_session["id"] is defined when login actually, so now we have several options to do so:
In config.php:
$db_people = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');
$db_login = new PDO('mysql:host=127.0.0.1;dbname=login;charset=UTF-8', 'root', 'pass');
And in login.php 1):
$stmt = $db_login->prepare("SELECT * FROM account WHERE id=? LIMIT 1");
$stmt->execute(array($_session["id"]));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Or this one is better when exclude query? Or the previous one is better?
And in login.php 2):
$query = "SELECT * FROM account WHERE id=? LIMIT 1";
$parameters = array($_session["id"]);
$statement = $db_login->prepare($query);
$statement->execute($parameters);
$results = $statement->fetch(PDO::FETCH_ASSOC);
And this login form:
public function login($user, $password)
{
global $web, $db;
if (!empty($user) && !empty($password))
{
$user = $web->esc($user);
$password = $web->doHash($user, $password);
$db->selectDb('login');
$qw = mysql_query("SELECT * FROM account WHERE username='".$user."' AND pass_hash='".$password."'");
if (mysql_num_rows($qw) > 0)
{
$result = mysql_fetch_array($qw);
$_session['name'] = $result['username'];
$_session['id'] = $result['id'];
return true;
}
else
return false;
}
else
return false;
}
Transfered into this form:
public function login($user, $password)
{
global $web, $db_login;
if (!empty($user) && !empty($password))
{
$user = $web->esc($user);
$password = $web->doHash($user, $password);
$stmt = $db_login->prepare("SELECT * FROM account WHERE username=? AND pass_hash=?");
$stmt->execute(array($user, $password));
$rows = $stmt->rowCount();
if ($rows > 0)
{
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_session['name'] = $result['username'];
$_session['id'] = $result['id'];
return true;
}
else
return false;
}
else
return false;
}
Is it ok or again do separate query or maybe do it in complete different way? Thank you all.
Also when there is multiple stmt should I use different name for it? For example I use stmt once and make a result1 after I do stmt second with result2 should I choose different name also for stmt variable or only result name is ok to be different?
OK so solution login.php 1) seems to be ok simple and no rush.
Also the login page seems to be working fine and therefore it should be according to every rules and ok :)

Categories