php SQL select query failing - php

I can't figure out why my SQL select query keeps failing - I am new to SQL so it might b a stupid mistake but I have not been able to find the answer in the documentation. Thanks a lot in advance
// connect to db
$mysqli = new mysqli("127.0.0.1", "maok08ab", "", "Portfolio");
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL";
}
$username=$_POST["username"];
$email=$_POST["email"];
$hash=$_POST["password"];
$query = "SELECT * FROM users WHERE username = '$username'";
$result= mysqli_query($mysqli, $query);
if ($result == FALSE)
{
apologize("something went wrong");
}

Since you're using an OOP connection you have to use OOP to perform the query:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $mysqli->query($query);
It states very clearly in the manual:
Link Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()
So your use of $result= mysqli_query($mysqli, $query); will not work as you would think. Make sure to stick with one method (OOP or procedural) throughout the life of your code.
In addition:
Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.

Related

Unable to login with email or mobile

I am trying to login with email or mobile (in PHP and MySQL). But I am unable to login.
Here is my code:
$sql = "SELECT * FROM tb_users WHERE (email='$loginEmailOrMobile' AND password='$loginPassword') OR (mobile_number='$loginEmailOrMobile' AND password='$loginPassword')";
$mysql = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($mysql) == 1)
{
echo "login successful";
$user = mysql_fetch_object($mysql);
echo $user->username;
}
else
{
die(mysql_error());
}
I think you have many problems in your code.
The mysql* extension is deprecated, and removed in PHP 7.
Plain passwords have poor security.
Prepared statements are recommanded when using variables.
You are handling an error when there is not.
You probably have no row (or more that 1) matching with your credentials so it's neither a success nor a MySQL error.
I will not cover all of this points in this answer in order to respect your original code, but I will try to explain many of them.
First, there is a tested and working code that does the job.
<?php
//Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "databaseName");
//These variables may be set from $_POST or anywhere
//it is only an example
$loginEmailOrMobile = 'an-email#example.com';
$loginPassword = '123456';
//!!Vulnerable to SQL injections**
$sql = "SELECT * FROM tb_users WHERE password = '$loginPassword' AND (email='$loginEmailOrMobile' OR mobile_number = '$loginEmailOrMobile')";
$result = $mysqli->query($sql);
//Only if we got 1 result
if (1 === mysqli_num_rows($result)) {
$user = mysqli_fetch_object($result);
echo $user->email;
} else {
die('We have not got only one result');
}
In this code you can see that:
Mysqli is used to perform the queries. It's really recommended to use mysqli instead of mysql for security reasons. Also, I'm using PHP 7 and I have not the mysql extension.
Because the case you were handling with mysql_error() was not en error, I have removed it in order to handling the case. If I get 0, or even 2 results, that's not a MySQL error, but perhaps I have no user or more than 1 with that credentials.
I have updated your SQL query in order to be less redundant but the logic is the same.
Your SQL query is not a prepared statement, I haven't touch it in order to respect your code and not to rewrite it entirely. But I really advise you to have a look at mysqli prepared statements
It seems you are currently using a plain password (unless you have already hashed it). It is recommanded to hash your passwords before inserting them into the database, and compare only the hashes. Please have a look to crypt().

PHP Login Form. Always wrong email, password

I'm having a little problem. I don't really know what I did wrong. I changed my Code from the deprecated php5 to php7 but after it. The Login doesnt work, as it should be
if(isset($_POST['is_login'])){
$sql = "SELECT * FROM ".$SETTINGS["USERS"]." WHERE `email` = '".mysqli_real_escape_string($_POST['email'])."' AND `password` = '".mysqli_real_escape_string($_POST['password'])."'";
$sql_result = mysqli_query ($connection,$sql) or die ('request "Could not execute SQL query" '.$sql);
$user = mysqli_fetch_assoc($sql_result);
if(!empty($user)){
$_SESSION['panel'] = $user;
$query = " UPDATE ".$SETTINGS["USERS"]." SET last_login = NOW() WHERE id=".$user['id'];
mysqli_query ($connection,$query ) or die ('request "Could not execute SQL query" '.$query);
}
else{
$error = 'Wrong email or password.';
The last Statement $error = 'Wrong email or password.'; is always being called. Thanks for help.
The reason is that mysqli_real_escape_string() requires a database connection be passed as the first argument.
http://php.net/manual/en/mysqli.real-escape-string.php
Better than that, use a prepared statement and do away with those pesky function/db calls.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Do keep in mind that if you intend on going live with this or are live, then use a safe hashing method such as password_hash(). I'm sure you'll like to keep your database intact.
password_hash() http://php.net/manual/en/function.password-hash.php
Debugging:
Using mysqli_error() on the query would have helped you during your transition.
http://php.net/manual/en/mysqli.error-list.php
Bit of a side note: if and when you decide to safely store passwords, remember to not use any escaping methods against passwords. One such as this 123'\abc<BR> would be considered as being valid. But by escaping it, that would be interpreted as 123\'\abc<BR> in turn rendering your verification method for it "null & void", and would fail silently because of it embedding the slash/escape quote in the hash. Both password_hash() and password_verify() take that into account.
password_verify() http://php.net/manual/en/function.password-verify.php

why mysql_num_rows always returns 0 in php

I am using php script to make login page. I use mysql_num_rows() method, it returns 1 if it matches first row only, it returns 0 when second or third row matches.
Here is My code:
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id,username,password FROM user_data WHERE username = '$username' and password = '$password'";
$result = mysqli_query($sql);
$count = mysqli_num_rows($result);
Here I also tried mysqli method too, but result are same.
Please Help
Seeing your previous question How to insert array of array in phpmyadmin using php
You're using the MySQL_ API to connect with (or most likely, seeing the use of mysql_ functions, and you probably thought that you would slip in a few i's to those MySQLi_ functions along with MySQL_.
Well, you can't.
You need to use the same API from connecting to querying.
However, if you are using MySQLi_ to connect with (which is unknown), you didn't pass the db connection to your query and as the first parameter.
For this line $result = mysqli_query($sql);
Which would look something like:
$result = mysqli_query($connection, $sql);
Also make sure that your POST arrays do contain values.
Consult the manual on connecting with the MySQLi_ API:
http://php.net/manual/en/function.mysqli-connect.php
Other links to consult to debug:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
And as stated in comments:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.

The difference between PDO sql statements and regular sql?

I've learned PHP from a book and its told me to use PDO objects or sql statements (I'm not sure if that's the right terminology, I apologize if it's not).
When I look up sql stuff, a lot of the times I see stuff like this:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
But in my code and in the book, I'm doing stuff like this:
global $db;
$query = "SELECT * FROM users WHERE username='$username'";
$results = $db->query($query);
$results = $results->fetch();
What's the difference between these two 'styles'?
First the function those are mysql_* (like mysql_query, mysql_connect etc) are deprecated and will not be supported in PHP future versions. So PDO or Mysqli are preferred way of communication with database.
The PDO 's prepared statements are used for avoiding SQL injection attacks. like in normal mysql_query you will use like this
$query = "SELECT * FROM users WHERE username='$username'";
$results = mysql_query($query);
but in PDO you have to use like this
$params = array(':username' => 'test', ':email' => $mail);
$pdo->prepare('
SELECT * FROM users
WHERE username = :username
AND email = :email');
$pdo->execute($params);
So PDO is recommended way. For more detail you can refer to
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://php.net/pdo
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
The first style was written long ago, or was written by people who stopped learning PHP before PHP5 came out. mysql_query is deprecated, and has been for a while now, and you should never be using it in a new project.
The second is using PDO, one of the newer database APIs. PDO supports a bunch of things that make working with SQL easier.
It's still pretty hideous as written, though. Most people would recommend using parameterized queries (a form of prepared statements) to separate the data from the SQL. This helps prevent "SQL injection", a process by which someone feeds you data that tricks your database into executing queries you never intended for it to.

Register user and checking if the user is in database

$query = mysql_query("SELECT * FROM dbusers WHERE email ='$_POST[email]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
NewUser();
}
else
{
echo "What's going on with this code?";
}
I'm trying to figure out why this isn't working. Supposed to check if the user trying to register with email is in the database. Thanks1
use mysql_num_rows function:
$query = mysql_query("SELECT * FROM dbusers WHERE email ='{$_POST['email']}'");
if(mysql_num_rows($query) >= 1) {
echo "What's going on with this code?";
}
else
{
NewUser();
}
Note: switch mysql_* functions to mysqli_* functions or use PDO libary. the are deprecated.
Try something like this
$email = $_POST['email'];
$query = mysql_query("SELECT * FROM `dbusers` WHERE `email` ='$email'") or die(mysql_error());
Disclaimer: Stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
As others have mentioned, you should be using some method to prevent SQL Injection against your database. You can string together a bunch of logic to do this for the deprecated MySQL driver, or you can use the prepared statements inside of MySQLI or PDO. Note, though, that if these extensions aren't configured to use "true prepared statements," that you might still need some light escaping against certain types of values.
Also, if you want it to be nominally faster for small data sets, and considerably faster for large data sets, instead of storing the user's email as you received it, reverse it first. For example, person#world.com would become moc.dlrow#nosrep. Storing emails like this will also make it possible to construct simpler queries when looking for all users who registered with an email from a specific domain.

Categories