num_rows keeps returning a null [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I honestly can't see why this doesn't work. I have checked it several times even compared it to other examples I have done that does work. Please note that I have taken it down to the simplest form so there is no sql injection protection. That comes later.
//user real escape string to prevent SQL injection
$username = $_POST['username'];
$password = $_POST['password'];
//check if username and password is blank
if (!$username || !$password)
die ("Not all the fields were filled in");
//Server details
$host = 'localhost';
$user = 'tm_user';
$password = 'password';
//The database name
$database = 'TransportMe';
// Create connection
$con = new mysqli($host, $user, $password, $database);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//since user and password is not blank, find user info using the email and password entered by user
$sql= "SELECT * FROM Users WHERE 'email'='$username' AND 'password' = '$password';";
//Get the results
$result = $con->query($sql);
//Check if null
if ($result->num_rows == null)
die("Null");

use backticks for columns in your query like this
$sql= "SELECT * FROM Users WHERE `email` = '$username' AND `password` = '$password'";

Your query should be:
//since user and password is not blank, find user info using the email and password entered by user
$sql= "SELECT * FROM `Users` WHERE `email` = '{$username}' AND `password` = '{$password}';";

Related

Can someone explain PHP SQL Select data to me?

I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.

Mysql Query not returning my results when adding variables into the query [duplicate]

This question already exists:
How to construct an SQL query correctly in a PHP script? [duplicate]
Closed 5 years ago.
If I run this with the query
"SELECT * FROM users";
It returns my result. But as soon as I run this
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
it doesn't.
If I run it in Mysql workbench without the variables it works. If I run echo the $_POST values they come through correctly.
I am stumped as to what I'm doing wrong PLEASE!! help me.
I also ran my code through https://phpcodechecker.com/ and it cant see any errors in my code.
This is the full function.
function login($username,$password){
global $db_conn;
$conn = new mysqli($db_conn['servername'], $db_conn['username'], $db_conn['password'], $db_conn['dbname']);
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
$login_result = $conn->query($login);
if ($login_result->num_rows > 0) {
$output = array();
while($row = $login_result->fetch_assoc()) {
$output[] = $row;
echo "".$row['name']."-".$row['password']."<br>";
}
} else {
echo "Invaild Login Details!"."<br>" ;
$conn->close();
return false;
}
}
Every time it says "Invalid Login Details!" But I know their is one result that gets returned.
What am I doing wrong?
Inserting variables into your SQL directly is a major source of SQL Injection Attacks. Use PDO for security.
https://www.php.net/manual/en/book.pdo.php#114974
change the query like this
$login = "SELECT * FROM users WHERE name= '$username' AND password= '$password'";
note: this method is prone to sql injection attacks. try prepared statements to avoid it
try with ''(single quote) for comparing name and password
"SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";
$login = "SELECT * FROM users WHERE name = '{$username}' AND password =
'{$password}' ";
You can simply specify the variables no need to go for string append to construct query in php
Eg :
Query = "SELECT * FROM `users` where username = '$username' AND password = '$password' " ;
try following code
$login = "SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";

What does the "Unrecognised SQL statement" mean when I am trying to use IF NOT EXISTS?

I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.

Use PHP variable to search through SQL database

I have a database called $addressdb. I want to search through a table on that database with a result the user inputted ($usersName). My mistake is probably really stupid. I am new with mySQL.
<?php
//IF THE LOGIN is submitted...
if ($_POST['Login']){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "addressdb";
$usersName = $_POST['users'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);
...
My line of error is
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
More specifically the variable call.
Best approach is :
$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";
Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.
Try something like this :
$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
You need to use quotes around your $userName.
$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";
But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);

Unknown column 'abcdefg' in 'where clause'23 [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
Ok so I am having some issues with a query. I am working to learn MySQLi as well so there may be some errors. I have a table named Authentication and in it, it has these columns
||id
||UserName
||Password
When running the query I am getting my username as the column name so it gives the unknown column error. I can not seem to see what is wrong with my code. Any help is appreciated.
<?php
// Report all errors
error_reporting(E_ALL);
session_start(); // Start PHP
// Get info sent to server from login form.
$my_username = $_POST['username'];
$my_password = $_POST['password'];
// MD5 Encrypt the password.
$my_password_md5 = md5($my_password);
// Connect to DB
$db = new MySQLi('localhost', 'user', 'password!', 'database');
if ($db->connect_error) {
$error = $db->connect_error;
}
//SQL query
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
$result = $db->query($sql) or die($db->error.__LINE__);
if($result = $db->query($sql))
$rows=mysqli_fetch_assoc($result);
// Count how many rows match that information.
$count=mysqli_num_rows($result);
// Check if there are any matches.
if($count==1)
{// If so, register $my_username, $my_password and redirect to the index page.
ini_set("session.gc_maxlifetime", "18000");
session_cache_expire(18000);
$cache_expire = session_cache_expire();
$_SESSION['username'] = $my_username;
$_SESSION['id'] = $rows['id'];
header("location:http://somesitegoeshere.com");
}
// If not, redirect back to the index page and provide an error.
else {
header("location:http://somesitgoeshere.com?err=1");
}
?>
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
You forgot to quote $my_username. so your query looks like WHERE 'username' = abcdefg HAVING...
Mysql thinks you're trying to compare to a column, put your username in quotes. Also put your password in quotes so it doesnt think your password is a column.
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = "$my_username" HAVING `username` = "$my_password_md5"
SQL;

Categories