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;
Related
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 3 years ago.
I'm trying to check the database for a taken username when the user signs up. The connection to the database works fine as a similar password will be added to the table.
$username = $_POST['user'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$s = 'SELECT * FROM users WHERE username = "$username"';
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if ($num == 1) {
echo "Username is taken";
}else {
table for users
It goes to the else and adds the username to the database anyways. I have checked to make sure there isn't more than one username, although a greater than sign would work better anyway. any ideas?
Your code must be using parameter binding to send the value of $username to the database, otherwise "$username" is treated as a literal string. It will also protect your from SQL injections.
It would probably be better to create a UNIQUE key on that column instead. If you want to do it in the application layer for whatever reason, you can fetch the result and use that.
$stmt = $con->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result()->fetch_all();
if ($result) {
echo "Username is taken";
} else {
// No such username in the database yet
}
This is not going to be very efficient, so we can simplify it using COUNT(1). It will return a single value containing the number of matching rows.
$stmt = $con->prepare('SELECT COUNT(1) FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$usernameTaken = $stmt->get_result()->fetch_row()[0];
if ($usernameTaken) {
echo "Username is taken";
} else {
// No such username in the database yet
}
For more explanation see https://phpdelusions.net/mysqli/check_value
$s = 'SELECT * FROM users WHERE username = "$username"';
You are using double quote inside single quote so there is no interpolation happening. Change the order to
$s = "SELECT * FROM users WHERE username = '{$username}'";
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}';";
While giving the correct login ID and Password which is there in the databse "tutorial" in table "users", it is giving me an error on the login.php which is being redirected.
Error is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''users' WHERE 'user' = 'XYZ'' at line 1
where XYZ is the username given from the user.
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "tutorial";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or die("Database not found");
$query = "SELECT * FROM 'users' WHERE 'user' = '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password' = '$inputpass'";
$result = mysql_query($query) or die(mysql_error());
$resultpass = mysql_query($querypass) or die( mysql_error());
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row["user"];
$serverpass = $row["password"];
if ($serveruser && $serverpass){
if(!$result){
die("Username Name or Password is invalid");
}
echo "<br><center>Database Output</b> </center><br><br> ";
mysql_close();
echo $inputpass;
echo $serverpass;
if($inputpass == $serverpass){
header('Location: home.php');
} else {
echo "Sorry, bad Login";
}
}
?>
Abhik Chakraborty is correct.
If you want to enclose field/column or table names you have to use backticks (so ` instead of '). The backtick is the diagonal quote on the button next to the "1", above "Tab".
To enclose field values you should use quotes the way you did.
Your corrected query: SELECT * FROM `users` WHERE `user` = '$inputuser';
HOWEVER, you should never, ever insert input gotten from a user directly into a query. If they type in something like a';DROP TABLE your_table_name; they can cause your database to start deleting tables, requesting records, etc.
Use correct escaping of user input: see this StackOverflow article on how to safely escape user input.
Instead of single quotes you should use back ticks (`)
I have written a code to check whether the username exists in the database or not. It seems to return that there is no such username exists even if there's a same username existing.
$conu=mysqli_connect("localhost","db_user","db_pass","db_name");
$result = mysql_query("SELECT 1 FROM member WHERE username = $username");
if ($result && mysql_num_rows($result) > 0) {
$user_err = "<i><span class='error'>Usernme already exists</span></i>";
$errflag = true;
}
elseif(preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
$user_err = "<i><span class='error'>Usernme must be bigger than 5 chararacters and can contain only digits, letters and underscore</span></i>";
$errflag = true;
}
Try
mysql_query("SELECT username FROM member WHERE username = '$username' LIMIT 1;");
SELECT 1 is not actually using the database; it's always returning 1, hence why your result is always the same regardless of the contents of the member table.
Usernames I take it are some sort of varchar? If that is the case, you might want to put its value in quotes:
$result = mysql_query("SELECT `username` FROM `member` WHERE `username` = '".$username."' LIMIT 1;");
your query is subject to sql injections btw.
At first, you are trying to return a column that probably doesn't exist: "1"
Second, I hope that you are cleaning the $username or else you are allowing anyone to inject your database.
The correct query is
mysql_query("SELECT * FROM `member` WHERE `username`='$username'");
You are using mysqli to connect, but mysql to perform your query.
When you SELECT 1 FROM member WHERE username = $username, the result will always be 1.
You need to put $username in the query in quotes. Something like SELECT username FROM member WHERE username = '$username'.
You forgot to include the part of the code for when there is no such username in your posting.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed last year.
I'm setting up a function in order to check if a passed username exists in the users table in my database. In order to do this, I'm using the following code:
function usernameCheck($username) {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$stmt = $con->prepare("SELECT username FROM users WHERE username = ':name'");
$stmt->bindParam(':name', $username);
$stmt->execute();
if($stmt->rowCount() > 0){
echo "exists!";
} else {
echo "non existant";
}
}
However, no matter what I try setting as $username, I can't get any exists! back. I've tried changing it around to check for an additional column, like userID, but it still doesn't work. I think my syntax is correct, but I'm new to PDO so I'm probably missing something easy to fix.
Thank you.
You don't need the escaping.
$stmt = $con->prepare("SELECT username FROM users WHERE username = :name");
Writing :name without any quotes should do the trick. The PDO-library already does the escaping for you.
Try the below SQL Query
$query="SELECT username FROM users WHERE username = 'name'";
$query_res = $con->query($query);
$count= count($query_res->fetchAll());
if($count > 0){
//user exists
}