How do i convert this to mysqli - php

Im having a problem converting this to mysqli from mysql, i've attempted what the php documentation said but i still can't get it. Any help would be appreciated.
return (mysql_result(mysql_query("SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;
I tried this:
return (mysqli_data_seek(mysqli_query($con,"SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;
Whole function:
function login($username, $password){
$con=mysqli_connect("127.0.0.1","root","","frostbase");
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysqli_data_seek(mysqli_query($con,"SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;
mysqli_close($con);
}

You can do it way better actually.
safeMysql is a tool that helps you to convert your ugly old mysql API-based code not to new ugly mysqli API-based code but use way better approach.
The point is that you must not use raw API calls in the application code, be it mysql, mysqli or PDO. But wrap them in a library that will do all the required operations like data binding, fetching, error handling, profiling and many more.
Frankly, you have only to write your query - the rest is done by the lib:
$sql = "SELECT 1 FROM users WHERE (username = ?s OR email = ?s) AND password = ?s";
return (bool)$db->getOne($sql, $username, $username, $password);
or, in a form of a function
function login($username, $password){
global $con; // you have to connect ONCE per application
$sql = "SELECT 1 FROM users WHERE (username = ?s OR email = ?s) AND password = ?s";
return (bool)$con->getOne($sql, $username, $username, $password);
}

Related

php: mysqli login script failing for unknown reason

So I have my log in script that I am trying to get to work, but when I try to log in it always says no even if the test I included below says expected:(password hash here) found: (same password hash here) I have changed the code so many times in attempts to fix it, and done a load of Google searches(for those who want to give me lmgtfy links) trying to fix it. I've included as much of the code as I can without having to add fake details so stack overflow would let me add more code:
Actual script:
else{
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username/password is incorrect';
} else {
echo "ok";
$_SESSION['user_id'] = $login;
header('Location: index2.php');
exit();
}
}
print_r($errors);
//echo "expected to see: ". $pass. " "; //this was a test
//echo "found: ".$passen; //this was too
Login function:
function login($username, $password){
$user_id = sanitize($username);
$db = get_my_db();
$username = sanitize($username);
$password = md5($password);
$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
return ($db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'") === 1) ? $user_id : false; }
And the sanitize() function is just mysqli_real_escape_string($data) if you want anything else, let me know, and i'll put it in. By the way, the tests script was this: and the expected function just turned the $password into an md5.
$res = $db->query("SELECT `password` FROM users WHERE username = '$username'");
$row = $res->fetch_assoc();
$pass = $row['password'];
$passen = expected($password);
I do not know where it fails, but a few tips:
use salted sha1 passwords
do not create functions like sanitize(),get_my_db(), those dont even speedup your work
mysqli_ should be called with $con first parameter, like mysqli_real_escape_string($con, $var);
to get working global $con in local function, write function
login() { global $con; }

How to login with bcrypt

I want to change my register/login pages from md5 to bcrypt. The register part is allright but I can't get the login part working good.
I am trying to work with a bcrypt library;https://github.com/ircmaxell/password_compat/blob/master/lib/password.php.
The original login function(without md5) looks like this;
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
return (mysql_result
(mysql_query
("SELECT COUNT(`user_id`)
FROM `users`
WHERE `username` = '$username'
AND `password` = '$password'"), 0) == 1) ? $user_id : false;
}
What I am trying to do is retrieve the database but with the original code is is not possible because of the mysql_result part.
I thought for example that;
function login($username, $password) {
$username = sanitize($username);
$user_query = mysql_query("SELECT `password` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_assoc($user_query);
$hash = $row['password'];
password_verify($password, $hash);
}
would solve this problem, but it isn't.
Is there a solution without mysql_fetch_assoc() here or am I trying to retieve the database wrong?
You need to set up password_verify like so :
function login($username, $password) {
$sql = "SELECT * FROM users WHERE username = :username"; // Select all info related to the USERNAME
$loginQ = $dbh->prepare($sql); // Prepare your query
$loginQ->bindParam(':username', $username); // Bind your variable
$loginQ->execute(); // Execute (TRUE or FALSE)
if ($loginQ) { // If TRUE
if ($loginQ->rowCount() == 1) { // You should only be returning 1 row with 1 username
$row = $loginQ->fetch(); // Fetch that row
$hash = $row['password']; // Use the row password and assign it to a variable
if (password_verify($password, $hash)) { // use passwd_compat function password_verify to check if it passes, if it does return TRUE
return TRUE;
}
}
}
}
Just from reading your code the issue I first noticed was that you are not returning a value whether it be
TRUE
or
FALSE
Also for another way to understand how to use password_verify you can also do it like so :
if (password_verify($form_password, $row['password'])) {
$_SESSION['LoggedIn'] = TRUE;
header("location: homepage.php");
} else {
Echo "Wrong password or username please <a href='index.php'><b>Retry!</b></a>";
}
and the next issue I noticed is that you are using unsafe and old functions (mysql_)
To help you with the later of the issues above I made a PDO version for you to use which has many more positives then mysql_ does.
Then to set up PDO look at this answer (yes it is mine - there a lot of good answers out there so do some research) This gives your the steps from setting up the PDO instance to actually using it. Any questions just ask.
More on PDO here.

Unable to solve PHP error message

Can anyone please help me with the following error. I am making a register and login function for my website. I have it connected to my local database and in there I have created a user. When I test that I can login and that username and password is recognised, it works as expected. But I get this error
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 17 in C:\xampp\htdocs\LoginAndRegistration\core\functions\users.php on line 34
And this is what I have on line 34
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Which is part of the following function
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
}
Ive been staring at it for ages now but cant seem to figure out the problem. Can anyone tell me what I am doing wrong?
Thanks
That line of code looks like that you want to check does username and password exist. You need to change your code to this:
return (mysql_result(mysql_query("SELECT COUNT(id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Also change (id) to your id name of column.
This error means the query failed. Always check if the query succeeded:
$q = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if ($q) {
if ($rows = mysql_num_rows($q)) {
// Continue operation, or set a flag
} else {
// No matching rows, throw an Exception or set a flag
}
} else {
// Something is wrong
die(mysql_error());
}
Your error probably comes from the fact that the query did not return any result at all because there was none with matching username and password.
I would really not stuff that much functions into each other. It looks overcomplicates, it does not leave any room to add error handling (like handling the case that is supposed to happen in your case), and it messes up PHP'S error reporting, because any error happening will be on the same code line.
Spread stuff out into multiple lines. It makes things clearer for you any anybody that reads your code, in enhances debugging activities, and is generally a good idea because of the lower line length.
You are getting a warning (not an error) because mysql_query at some times, it won't return any rows, so trying to get the first row with mysql_result when there are not rows, will raise the warning.
You can try:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($query) > 0)
return true;
else
return false;
}
With the depreciation argument aside, use mysql_num_rows instead of mysql_result.
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'")) == 1) ? true : false;
}
try this
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'") ;
if (mysql_num_rows($query) > 0 ) {
$data = true ;
}else {
$data = false ;
}
return $data ;
}

PHP/SQLite Accepting Incorrect Post Values

I am creating a simple PHP login system using SQLite, when when the user posts the the HTML form, the system guides them to the "members only page" regardless of what they entered. Here is my form processing code:
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$database = new PDO("sqlite:database.sqlite");
$result = $database -> query("SELECT COUNT (*) FROM accounts WHERE username = '$username' AND password = '$password'");
if ($result > 0)
{
setcookie("session", "Cool", time()+3600);
header("location:index.php");
}
else
{
echo "Failure";
}
?>
Help!
I think it should be...
if ($result->rowCount() > 0) ...
AND: use prepared statements to avoid SQL-injection, don't store uncrypted passwords in your DB, it's a huge security-problem.
Try this (You shouldn't need count, just a simple logical statement):
$query = "SELECT * FROM accounts WHERE username = :username AND password = :password";
$stmt = $database->prepare($query);
$stmt->execute(array(":username"=>$username, "password"=>$password));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
//Success
setcookie("session", "Cool", time()+3600);
header("location:index.php");
}
// Not successful.
return null;

PDO script to get the amount of rows not working?

I'm new to PDO PHP (just started today). I am attempting too write a login function, but it is returning false, even though i know the credentials are correct.
I think is is the attempt to get the amount of rows which is tripping the script up, can you help?
function check_login($email, $username, $password)
{
$host = 'localhost';
$port = 3306;
$database = 'example';
$username = 'root';
$password = '';
$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username, $password);
$password = md5($password);
$statement = $db->prepare("SELECT * FROM users WHERE email = ? or username = ? and password = ?");
$statement->execute(array($email, $username, $password));
while ($result = $statement->fetchObject()) {
$sql = "SELECT count(*) FROM users WHERE email = ? or username = ? and password = ?";
$result1 = $db->prepare($sql);
$result1->execute(array($email, $username, $password));
$number_of_rows = $result1->fetchColumn();
if ($number_of_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $result->uid;
return TRUE;
}
else
{
return FALSE;
}
}
}
This:
WHERE email = ? or username = ? and password = ?
... equals this:
WHERE email = ? or (username = ? and password = ?)
... due to operator precedence. That means that if you validate with an e-mail address, you are not required to provide a valid password to log in.
Once you've found out whether the user exists, you make a second query to count the number of matching users. The database table should not be able to hold duplicate users in the first place! Columns username and email should be defined as unique indexes.
There's no point in using a while loop if it's going to return in the first iteration. It may work, but it's confusing.
This should be enough:
$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($email, $username, $password));
if ($result = $statement->fetchObject()) {
$_SESSION['login'] = true;
$_SESSION['uid'] = $result->uid;
return TRUE;
}else{
return FALSE;
}
Edit: BTW, you should not be storing passwords in plain text. Countless sites have been hacked and their passwords stolen. Google for salted passwords.

Categories