I have a basic login code, where the user enters a username and a password, hits 'Submit', and then a mySQL query checks in the database if the username corresponds to the password.
Here is the query, with 'pseudo' as the username typed by the user and 'mot_de_passe' as the password typed in.
$reponse = $bdd->query('SELECT * FROM user_data WHERE username = '.$_POST['pseudo'].' AND password = '.$_POST['mot_de_passe'].' ');
Without the 'AND...' part, I can check if the username exists, but then when I add the 'AND...' part, the query doesn't work, and the 'AND' is not in the same color as 'SELECT * FROM'and 'WHERE'
I have tried dots, simple quotes, quotes, but nothing changes.
Thanks in advance.
You must use " or ' about string in SQL
$reponse = $bdd->query('SELECT * FROM user_data WHERE username = "'.$_POST['pseudo'].'" AND password = "'.$_POST['mot_de_passe'].'" ');
And your code can't prevent SQL INJECTION attack.
Please use prepared statement or bind param.
Use the below code and check weather it works or not.
$reponse = $bdd->query('SELECT * FROM user_data WHERE username = ' .
$_POST['pseudo'] . ' AND password = ' . $_POST['mot_de_passe'] );
also check your password type stored in your database and try to match that
$reponse = $bdd->query('SELECT * FROM user_data WHERE password = ' .
$_POST['mot_de_passe'] );
if working then check your database keys and match your password spelling and things like that..
Related
On my form page, I have two textboxes with the names name and password.
When the user hits submit, it sends that data into two columns in a MySQL database named 'name' and 'password'.
After the data is recorded (which is the part I understand and don't need help with), I want the user to be at the sign-in page and type in his/her name and password and only be allowed into the site if the name and password data already exist in the database (part that I don't understand).
Would I use the following query :
SELECT * FROM tablename WHERE name & password = "'$_POST[name]', $_POST[password]'
You should use AND or && instead of just a single ampersand (&), and separate the variables to be binded accordingly to their column name.
You should also consider sanitizing your variables before using them to your queries. You can use *_real_escape_string() to prevent SQL injections.
$name = mysql_real_escape_string($_POST["name"]);
$password = mysql_real_escape_string($_POST["password"]);
"SELECT * FROM tablename WHERE name = '".$name."' AND password = '".$password."'"
But the best recommendation that I can give to you is to use prepared statement rather than the deprecated mysql_*
if($stmt = $con->prepare("SELECT * FROM tablename WHERE name = ? AND password = ?")){ /* PREPARE THE QUERY; $con SHOULD BE ESTABLISHED FIRST USING ALSO mysqli */
$stmt->bind_param("ss",$_POST["name"],$_POST["password"]); /* BIND THESE VARIABLES TO YOUR QUERY; s STANDS FOR STRINGS */
$stmt->execute(); /* EXECUTE THE QUERY */
$noofrows = $stmt->num_rows; /* STORE THE NUMBER OF ROW RESULTS */
$stmt->close(); /* CLOSE THE STATEMENT */
} /* CLOSE THE PREPARED STATEMENT */
For securing password, you could also look at password_hash().
Please Always use Prepared statement to execute SQL code with Variable coming from outside your code. Concatenating variable from user input into SQL code is dangerous ( consider SQL injection ), you could use prepared statement with mysqli or PDO ( recommended ).
Mysqli example:
$mysqli = new mysqli("example.com", "user", "password", "database");
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $user,$password);
$stmt->execute();
if($stmt->num_rows!=1) {
// check failed
}else{
// check success
}
PDO example (recommended )
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $dbh->prepare($query);
$stmt->bindParam(1,$user);
$stmt->bindParam(2,$password);
$stmt->execute();
if($sth->fetchAll()) {
// check success
}else{
// check failure
}
Additionally you should also consider using some form of 1-way password encryption ( password hashing ) before storing it in your database and compare it to the hash( the most accepted way to do it is using Bcrypt).
You can use something like
SELECT count(*) FROM tablename WHERE name = "'.$_POST[name].' AND password = "'. $_POST[password].'"
You should expect count to be exactly 1 - indicating valid user, 0 - indicating invalid user
Anything greater than 1 should be invalid scenario indicating some kind of inconsistency in your database...
You should assign the variables to name & pass subsequently.
You can try this:
$con = mysqli_connect("localhost","YOURUSER","YOURPASS","YOURDB");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
$user
= mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$query = "select * from tablename where user ='$user' AND password='$pass' ";
$run = mysqli_query($con,$query);
$check = mysqli_num_rows($run );
if($check == 0)
{
echo "<script> alert('Password or Email is wrong,try again!')</script>";
}
else
{
//get a session for user
$_SESSION['user']=$user;
// head to index.php; you can just put index.php if you like
echo"<script>window.open('index.php?login=Welcome to Admin Area!','_self')</script>";
}
$account = "proot";
$sql_check_account = mysqli_query($connect, "SELECT username FROM proot_accounts WHERE username = $account");
if(!$sql_check_account)
die(mysqli_error($connect));
Return :
Unknown column 'proot' in 'where clause'
Same with :
$sql_check_account = mysqli_query($connect, 'SELECT username FROM proot_accounts WHERE username = "'.$account.'"');
Or
$sql_check_account = mysqli_query($connect, "SELECT username FROM proot_accounts WHERE username =".$account);
What can make the variable $account perform as a column ? I don't get the problem here...
Thanks !
You need to put quotes around it.
mysqli_query($connect, "SELECT username FROM proot_accounts WHERE username = '$account'");
You should also explore prepared SQL statements in PHP. They will save a lot of these formatting headaches.
I think this is a quoting issue. This:
"SELECT username FROM proot_accounts WHERE username = $account"
will get you this string:
SELECT username FROM proot_accounts WHERE username = proot
In this case MySQL is thinking proot is a column name, because proot is not in quotes at all.
This:
'SELECT username FROM proot_accounts WHERE username = "'.$account.'"'
will get you this string:
SELECT username FROM proot_accounts WHERE username = "proot"
In this case, MySQL may still think "proot" is a column name, depending on the SQL mode. Since you are still getting the same error when you use this code, it looks like your database is set to ANSI_QUOTES mode. In this mode, text inside quotation marks will be interpreted as an column identifier, not a literal value.
Using this:
"SELECT username FROM proot_accounts WHERE username = '$account'"
will get you this string:
SELECT username FROM proot_accounts WHERE username = 'proot'
Using ' instead of " should ensure that MySQL will treat proot like a literal value instead of a column identifier regardless of the SQL mode.
I have recently started to learn php and currently i am working on a project in which i have to send and get information to a MSSQLS Database. I have heard PDO is the right way, so i managed to make the following code reading some tutorial:
$email = $_POST['email'];
$password = $_POST['password']; // The hashed password.
$connection = new PDO('sqlsrv:Server='. HOST .';Database=' . DATABASE, USER, PASSWORD);
$connection->query("use sub_secure_login");
$query = 'SELECT ID, username, password FROM members WHERE email = ?';
// Prepare the query
$stmt = $connection->prepare($query);
// Set the arguments array
$array = array($email);
// Execute the prepared query with the specified params
$stmt->execute($array);
$fetch = $stmt->fetch();
error_log('id: ' . $fetch['ID']);
error_log(' username: ' . $fetch['username']);
error_log(' password: ' . $fetch['password']);
SQL table name: members
with the following columns: ID - username - password
Basically, $email = $_POST['email'] is submited by a login form.
I dont know what is wrong in my code. Not sure if it is the query that is wrong, or something else. No error is shown in php_error_log and the loggs that i made are returning nothing but id, username, password.
Any help would be apreciated, and if possible, more information about using PDO, prepared statments with MSSQLS
This has surely come up before but I haven't found a solution. I am trying to select username and password from a database to verify users a simple login script. It should simply find a row in the users table with a username and password matching those submitted through the login form.
I can match the username without any problem but not the password and I have no idea why.
The table contains columns called "username" and "password" and there is only 1 row in the table with a username 'admin' and a password 'testpassword'.
Here is the function containing three options - options 1 and 4 work, the other two don't. Option 2 is the same as option 1 except it looks up a different column. I have checked that the column name in the query matches the columns in the table and that the submitted values match. I'm not getting any error messages and can't see what might be wrong (something basic, I'm sure...).
function new_session ($username, $pw, $inactive) {
// echo statements verify that variable match database values
echo "<h2>username = " . $username . "</h2>";
echo "<h2>password = " . $pw . "</h2>";
echo "<h2>inactive = " . $inactive . "</h2>";
$db = mydb::getConnection();
//option 1
$statement = $db->prepare('SELECT * FROM users WHERE username = :parameter');
$statement->bindValue(':parameter', $username);
//option 2
//$statement = $db->prepare('SELECT * FROM users WHERE password = :parameter');
//$statement->bindValue(':parameter', $pw);
//option 3
//$statement = $db->prepare('SELECT * FROM users WHERE password = :parameter1 AND username = :parameter2');
//$statement->bindValue(':parameter1', $username);
//$statement->bindValue(':parameter2', $pw);
//option 4
//$statement = $db->prepare('SELECT * FROM users WHERE username = "admin" AND password = "testpassword"');
$statement->execute();
$row = $statement->fetchAll();
if (count($row) == 1) {
// SESSION data is set here for options 1 and 4
}
}
First thing you need to check is if the passwords in your data base are hashed. They probably should be, and if they are you need to compare using the hashing function PASSWORD
$statement = $db->prepare('SELECT * FROM users WHERE password = PASSWORD(:parameter)');
$statement->bindValue(':parameter', $pw);
Now, if your passwords aren't hashed (shame on you), you might have a different problem. As you can see in the above, password is a function name in mysql. It might be having problems parsing your statement because you are using password as a column name. Put tick-marks around the column name password. Like this:
$statement = $db->prepare('SELECT * FROM users WHERE `password` = :parameter');
$statement->bindValue(':parameter', $pw);
Notice that those are tick marks, not a single quote. They are found on the same key that ~ is on, above the tab key. These tick marks will indicate that password is a column name.
The word "PASSWORD" is a mysql command. so escape it first like this:
//option 3
//$statement = $db->prepare('SELECT * FROM users WHERE `password` = :parameter1 AND username = :parameter2')
If this query gives error, then I think you have your password encoded.
Then use this for md5:
$statement->bindValue(':parameter', md5($pw));
And for sha1:
$statement->bindValue(':parameter', sha1($pw));
I see no other errors which might could result in no rows :o
Thanks for all the suggestions and taking time to look at this, I have escaped the word password as suggested however I'm ashamed to say the problem was that the maxlength on my password form input was trimming the last character and I didn't spot it.
I am using the stored $_SESSION username:
$usernameunesc = htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8');
and escaping the variable as follows:
$username = mysqli_real_escape_string($link, $usernameunesc);
and then using it to perform the following query:
$query = mysqli_query($link, "SELECT id FROM users WHERE username = '".$username."'");
The last query returns an output of
1111
If I remove $username from the query and change it to 'demo' (which is what the username actually is) the query returns an id of 12 successfully, but using the $username variable does not work. Am I not properly escaping the string? Is there a better way to do this? By the way, I can also perform the query in the SQL command line and it works fine, so I know the query isn't the problem.
As you are using mysqli, I suggest you use a prepared statement - it will automatically escape the variable.
if ($stmt = $mysqli->prepare("SELECT id FROM users WHERE username =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $usernameunesc);
/* execute query */
$stmt->execute();
}
Full example right here http://php.net/manual/en/mysqli.prepare.php