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
}
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 6 years ago.
I've been stuck on this for about 3 days now and asked multiple people about this and no one seems to have an answer to me why this is not working. I cannot figure out why they aren't binding because the bindings work on the select statement but not the update. I know for a fact that $sessCheck['userid'] and $sessCheck['hwid'] are being set because I already printed them out to check if they were null or something.
The request inbound from slim
{"userid": "1000","hwid":"TESTING"}
The function
function updateHWID(){
$request = Slim::getInstance()->request();
//$bsreq = utf8_encode();
$sessCheck = json_decode($request->getBody(), true, 9 );
$db = getConnection();
$sql = "SELECT userid,hwID FROM accounts WHERE userid = :userid";
$stuff = $db->prepare($sql);
$stuff->bindParam("userid", $sessCheck['userid']);
$stuff->execute();
$db = null;
$rows = $stuff->fetch(PDO::FETCH_ASSOC);
if ($rows['hwID'] != $sessCheck['hwid']) {
$sql2 = "UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid';";
try {
$db2 = getConnection();
$stmt = $db2->prepare($sql2);
//these two param's are not binding
$stmt->bindParam("userid", $sessCheck['userid']);
$stmt->bindParam("hwid", $sessCheck['hwid']);
$stmt->execute();
//$rt = $stmt->fetch(PDO::FETCH_ASSOC);
//$stmt->debugDumpParams();
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
This is the result incoming on the sql log
1372 Query UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid'
I've also tried this as well as using the which also didn't work
$stmt->bindParam(":userid", $sessCheck['userid']);
$stmt->bindParam(":hwid", $sessCheck['hwid']);
Then I tried this too and it didn't work
$stmt = $db2->prepare("UPDATE accounts SET hwID='?' WHERE userID = '?';");
$stmt->bindParam(1, $sessCheck['hwid'], PDO::PARAM_STR);
$stmt->bindParam(2, $sessCheck['userid'], PDO::PARAM_INT);
Take the binded parameter names out of their single quotes.
so:
$sql2 = "UPDATE accounts SET hwID=:hwid WHERE userID = :userid;";
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i am trying to check a data existence from mysql table but following script not working. bellow my codes are provided please find out where is my mistake there.
<?php
//including the database files
include("../inc/settings.php");
$email = $_POST['email'];
$password = $_POST['password'];
$query = mysql_query("SELECT easy123 FROM users WHERE email=$email", $conn);
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
echo "this username not used";
}
?>
The error i am getting is-
Warning: mysql_query() expects parameter 2 to be resource, object
given in C:\xampp\htdocs\myfiles\Easy123\master\login.php on line 8
Warning: mysql_num_rows() expects parameter 1 to be resource, null
given in C:\xampp\htdocs\myfiles\Easy123\master\login.php on line 10
this username not used
First of all, make sure your database connection is correctly set up. The error you're getting clearly says that your $conn variable isn't a valid resource.
Also, use prepared statements and parameterized queries. Do not use PHP variables within your query string, it's not secure at all. Use instead PDO or MySQLi
Using PDO:
$stmt = $pdo->prepare('SELECT easy123 FROM users WHERE email = :email');
$stmt->execute(array('email' => $email));
foreach ($stmt as $row) {
// do something with $row
}
Using MySQLi:
$stmt = $dbConnection->prepare('SELECT easy123 FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Your $query seems to be wrong. Try this:
$query = mysql_query("SELECT easy123 FROM users WHERE email='$email'", $conn);
Make sure $conn is properly defined aswell.
So I'm new to php and mysql and over the past few days have created a log in system using php and mysql. I am trying to make a function where a user can change their password with the following query:
$query2 = mysql_query("SELECT password FROM adminusr WHERE id =$idToChange");
$result = mysql_query($query2) or die($idToChange.mysql_error());
With SELECT statements you only select rows. To change them you need UPDATE. Consider using PDO because mysql_* functions are deprecated. Also try to hash your passwords and don't store them in plain text.
You need something like this:
$query2 = mysql_query("UPDATE adminusr SET password = '$new_password' WHERE id = '$idToChange'");
Using PDO
//Make the connection using PDO
try {
$conn = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
//Make your query
$sql = 'UPDATE adminusr SET password = :new_password WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':new_password'=>$new_password, ':id'=>$idToChange));
EDIT answering to comment
Then you need to have also username and password fields at your form. So, you need four fields: username, oldPassword, newPassword, confirmNewPassword. Before the update statement you need to select the user having credentials username, oldPassword. If you find only one then you have to check if newPassword and confirmNewPassword match. If match then proceed to update. Otherwise print some error message.
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;