Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a basic question, just starting to dive into PHP and Mysql.
There seems to be an error in this construct, can anyone help me?
Thanks!
K.
if ($password = mysqli_query ("SELECT password FROM users WHERE firstname = '$username'")) {
echo "password success!";
}
else {
echo "Password fail!";
}
Step one when you have a question, refer to the manual.
http://php.net/manual/en/mysqli.query.php
Now are you using the object oriented style or procedural? You are missing the link in either approach.
Once you resolve that you have the issue that the function doesn't return a string.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So with that you'll either get false on an error or a mysqli_result object. To parse through the object use fetch; http://php.net/manual/en/mysqli-stmt.fetch.php.
But first you should be using prepared statements which will greatly reduce your chances of being SQL injected; http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
After that you should pass the password in with your query because you can just have mysql evaluate that the password and username match up then if you get a returned result you know the data is valid.
Additional note: you shouldn't store passwords in plain text, if you are.
Also the = assigns a value. To compare two values you need to use == or ===. For a longer write up see http://php.net/manual/en/language.operators.comparison.php.
In mysqli you have to store your db_connection into a variable and have to pass in every query. Below is the complete path what you have to follow:
Create connection with database by using host_name, user_name, password,db_name. And store connection into a variable.
You can run any query by passing connection variable.
below code is:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($password = mysqli_query ($con, "SELECT password FROM users WHERE firstname = '$username'")) {
echo "password success!";
}
else {
echo "Password fail!";
}
?>
Assuming your connection details are stored in a variable $db
Firstly, you need to provide mysqli_query with the database connection resource in procedural mode.
$password = mysqli_query($db, "SELECT password FROM users WHERE firstname = '$username'");
Related
This question already has answers here:
mysqli_affected_rows in PHP insert
(3 answers)
Closed 6 years ago.
I'm working with PHP and mysqli, what the program is doing is that it is asking for a reset code and email address if the email add and reset code are found in the database it sets the password,this part of the function is working,
I need help with this part: what I need to do is tell the user if the password was set or not so if the update was successful or not.
What I'm working on:
$uinsert = "UPDATE member SET password = '$password' WHERE emailadd = '$emailadd' AND resetCode = '$resetcode'";
$update = mysqli_query($mysqli, $uinsert) or die(mysqli_error($mysqli));
if(mysqli_affected_rows($update) == 1 ){ //ifnum
header("location: ../index.php"); // Redirecting To Other Page
}
else{
echo "<script> alert('Incorrect code, try again!');</script>";
}
Note: $mysqli is my connection string
"#Fred-ii- Thank you so much that works! – Coffee coder 58 secs ago"
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all.
Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.
affected_rows() uses the connection, not the one for the query.
http://php.net/manual/en/mysqli.affected-rows.php
Plus, if you're storing plain text passwords, use password_hash() since it's much safer:
http://php.net/manual/en/function.password-hash.php
Sidenote: If you do decide to move over to that function, make sure that you do not manipulate the password at all. Hashing/verifying it takes care of that and you may be doing more harm than good in doing so and limiting passwords.
I.e.: A valid password of test'123 would be interpreted as test\'123 and rendering FALSE when using real_escape_string() for example.
Or you may still be using hash_hmac as per your other question Comparing/check if correct Password from mysqli database [hash_hmac]
and a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
It is also best to add exit; after header. Otherwise, your code may want to continue to execute.
header("location: ../index.php");
exit;
Change the parameter of mysqli_affected_rows(), the parameters must be the mysql connection
mysqli_affected_rows($update)
to
mysqli_affected_rows($mysqli)
Please see this reference
https://www.w3schools.com/php/func_mysqli_affected_rows.asp
if (mysqli_affected_rows($mysqli) == 1 ) {
Because mysqli_affected_rows() does not use the query $update as its parameter, it uses the connection variable: $mysqli
pass your mysqli connection object ($connection) to mysqli_affected_rows(connection_object) to check affected rows.
connection_object is like - $con=mysqli_connect("localhost","bd_user","db_password","your_db_name");
So , code will be
if(mysqli_affected_rows($con)== 1 ){
header("location: ../index.php");
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Background -
I have spent the last hour or so looking through various posts sites and so on to see why my password checking function has suddenly stopped working.
Every time I try to use it, it returns false, including when the inputted password is correct.
I have echoed my input and my hash, both of which match fine (by comparing the hash in the table to the one echoed).
However, when these variables are put through password_verify, it returns false 100% of the time.
What do I think is wrong? - Based on a post from an external site, I think this is due to the way that my hashedPassword variable is being parsed. When is compares the two, something goes wrong in the variable type and returns false.
What does my code and database look like? -
users table. Contains other columns.
userId | username | password
----------------------------
1 | example | temp1
Class containing the password checker function. (Have trimmed away try/catch)
public function checkPasswordCorrect($username, $password) { // Returns true is the entered password is correct and false if it isn't.
// This creates a mysqli context to run the connection through.
$mysqli = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbPlusPlus);
// If there is an error connecting to the database, it will be printed and the process will close.
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT password FROM users WHERE username='$username'";
$result = $mysqli->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$hashedPassword = $row["password"];
$mysqli->close();
echo $password."<br>".$hashedPassword."<br>"; // The input is correct and the hash matches that in the table.
// We return a value of true or false, depending on the outcome of the verification.
if(password_verify($password, $hashedPassword)) {
echo "return true";
return true;
}
else {
echo "return false";
return false;
}
}
By echoing $hashedPassword just before using password_verify, the hash matches by manually checking it, as you can see by the output below.
temp0022
$2y$10$9TgjJzSaqOB
return false
What am I asking? -
Is there a better way of checking password inputs, more specifically, the way I'm pulling the information from the table (there must be some simpler way of doing this).
Is the variable parsing to blame? Is there any documentation or articles available for this topic that I haven't seen?
What am I aware of? - My usage of mysqli is shocking, I'm new to it. I am also aware that there are similar answers out there, but seem to be down to some kind of syntax error more than anything else.
Thank you for taking the time to help! :D
For all of those of you who are worried that I'm going to be hit by SQL injection attacks: I have since modified this example code
massively and am using prepared, statements. Thank you for your
concern :)
Check your table structure. Your hash field needs to be of length 60 (for PASSWORD_BCRYPT) or 255 (for PASSWORD_DEFAULT) (ref) to save the whole hash. What you got from the database is 18 characters long. You probably have it as VARCHAR(18), so it's getting truncated upon saving, which is why you're not getting a match.
Edit: Added length for the PASSWORD_DEFAULT algorithm. Thanks #Don'tPanic.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Whenever I try to run this code it shows an error. I am a Newbie to PHP,MySQL.The code is as follows:
$id=mysqli_connect("localhost","root","") or die("Could not connect to MySQL server.");
$query="Select Code,Name from world.Country limit 10,5";
$query_results=mysqli_query($id,$query);
if($query_results==false)
{
echo"Failed";
}
while($row=mysql_fetch_array($query_results,MYSQL_BOTH))
{
$Countrycode= $row['Code'];
$Countryname= $row['Name'];
print "$country_name($country_code)<br>\n";`//No display`
}
mysqli_close($id);
Edit
Interestingly, even though you are not providing a default database to select, your query is still working because you are providng the database identifier in the query itself. So my fisrt suggestion is not the actual problem that you have. Its only the fact that you are using mysql_fetch_array instead of mysqli_fetch_array that you are seeing that error.
Previous answer
You have not selected any database to work on. You are missing a call for
mysqli_select_db($id,$databaseName);
Then you are mixing up mysql_* functions with mysqli_*. Read the MySQLi Manual for proper usage instructions. You can also provide the database name when connecting, like this
mysqli_connect("localhost","root","password","database")
Then You have to fetch the results using mysqli, not mysql
mysqli_fetch_array
You miss the DB name in connection:
$id=mysqli_connect("localhost","root","","DBNAME") or die("Could not connect to MySQL server.");
And change mysql_fetch_array to mysqli_fetch_array
while($row=mysqli_fetch_array($query_results)){
......
......
}
$id=mysqli_connect("localhost","root","",$databaseName) or die("Could not connect to MySQL server.");
$query="Select Code,Name from world.Country limit 10,5";
$query_results=mysqli_query($id,$query);
if($query_results==false) {
echo"Failed";
}
while($row=mysqli_fetch_array($query_results,MYSQL_BOTH)){ // You used mysql_fetch_array
$Countrycode= $row['Code'];
$Countryname= $row['Name'];
print "$country_name($country_code)<br>\n";`//No display`
}
mysqli_close($id);
if you are using mysqli then you should use mysqli_fetch_array.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a problem with a bit of code and connat figure why it is going wrong
//Searches the database for the username
$mysqli_username = mysqli_query($mysqli, "SELECT username FROM ajbs_users WHERE username=`".$username."`");
// if name does not exist
if ($mysqli_username == null)
{
echo "<p>Username was inccorect, or user does not exist</p>";
}
else //if username is correct
{
//finds and stores password of the user
$mysqli_userPassword = mysqli_query($mysqli, "SELECT password FROM ajbs_users WHERE password=`".$password."`");
if ($mysqli_userPassword != $password) //checks password matches from user
{
echo "<p>Password was inccorrect</p>";
}
else
{
//Login
echo "<p>You have been logged in";
// Re directs to other page after creating a session
}
}
The script keeps outputting the "Password is incorrect" statement.
There are a number of problems with your code:
mysqli_query() does not return rows from the database, it returns a resource from which you can fetch rows from the database. Or else it returns false if the query produces a parse error or an execution error. You need to check for these error cases.
Or else use mysqli_report(MYSQLI_REPORT_STRICT) to configure mysqli to throw exceptions on error (if you know how to program with exceptions).
You are using the back-ticks around the values $username and $password. Back-ticks are for delimiting identifiers like table names and column names. For string values and date values, use single quotes. Double-quotes are used the same as single quotes by default, for strings and dates. But this can change if you set MySQL into ANSI mode, then double-quotes are used like back-ticks, for identifiers. See MySQL's different quote marks
You are interpolating variables directly into your SQL expressions, which is not safe unless you've been very careful to escape them. This is how SQL injection happens. Read What is SQL injection? and How can I prevent SQL injection in PHP? You should use prepared statements and add dynamic elements to the query using parameters.
Keep in mind that if you use parameters, the quote issue disappears. You don't put any type of quotes around parameters. Using parameters is both easier and more secure than interpolating variables into strings.
And some problems with your logic or application design:
You checked if a username exists. Then if it does, you checked if a password exists. But in your code, the password is not necessarily used by the same username. Your code doesn't check that the same user has that password, only that any user has that password.
What this means is that I can hack your site if I can register one username with password I know, say 'xyzzy'. Then I can log in as any other username, using password 'xyzzy'.
It's not a good security practice to tell the user whether the username or the password is incorrect. They should only be told that the login failed. If they're a hacker, it can be useful to them to know that they're on the right track, that is, they have chosen a valid username, they just need to guess the password. You might want to log the information for your own troubleshooting, but be more vague as you report to the user.
You shouldn't store a plaintext password. Store a hash of the password. Also store a random salt per user, and use that in the hash calculation. See You're Probably Storing Passwords Incorrectly and What data type to use for hashed password field and what length?
You can do this search with one query instead of two if you compare the username and password in one query. I search for the username in the WHERE clause, and then return the result of a boolean comparison of the stored password hash against the hash of the user's input.
So here's how I would write it, keeping in mind all the points from above.
/*
* Search the database for the username, and report if the password matches
*/
$sql = "SELECT (password = SHA2(CONCAT(?, salt), 256)) AS password_matches
FROM ajbs_users WHERE username = ?";
if (($stmt = $mysqli->prepare($sql)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
}
$stmt->bind_param("ss", $password, $username);
if ($stmt->execute() === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
$stmt->bind_result($password_matches);
if ($stmt->fetch()) {
if ($password_matches) {
echo "<p>You have been logged in";
// Re directs to other page after creating a session
} else {
error_log("Login attempted with user '$username', but password was incorrect.");
}
} else {
error_log("Login attempted with user '$username', but user does not exist.");
}
// Tell the user only what they need to know.
echo "<p>Login failed. Username or password was incorrect</p>";
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have searched google, read in the PHP manual and tried several tutorials to make a secure login script for mysqli and PHP. Does anyone know of one that actually works without md5?
I would like to see some working code or a tutorial if possible.
Mine won't actually query the db or return a value, even after hardcoding the values into the script... I'm looking for something like:
connect using the 'connectdb' file
post the user/pwd from the form
query db for user/pwd
set session with username
etc.
This is my code that doesn't work:
<?php
include ("conectionlink.php");
//connection errors if any...
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$userid = htmlentities($_POST['userid'], ENT_QUOTES);
$password = htmlentities($_POST['password'], ENT_QUOTES);
//create a prepared statement
if ($stmt = $mysqli->prepare("SELECT userid, password FROM admins WHERE userid=? and password=?")) {
// bind parameters-define them...
$stmt->bind_param("is", $userid, $password);
//execute...
$stmt->execute();
// bind result variables
$stmt->bind_result($userid,$password)
//fetch value
$stmt->fetch();
var_dump($userid, $password);
printf("%n is associated with %s", $userid, $password);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I receive the following error message:
According to the PHP documentation for mysqli, bind_result() syntax should be in one line, rather than performing multiple binds:
bind_result ( mixed &$var1 [, mixed &$... ] )
So, instead of this:
$stmt->bind_result($userid);
$stmt->bind_result($password);
try doing this:
$stmt->bind_result($userid,$password);
You seem to be treating the userid column as containing an integer, when I suspect you are really receiving a string. You initialize $userid like this:
$userid = htmlentities($_POST['userid'], ENT_QUOTES);
Then you use it in a SELECT and treat it as an integer in your bind_param() call. So, you're treating it like an integer (which seems unlikely in a $_POST variable -- I expect you are really receiving a string username, not an integer ID).
You also have a problem with your call to printf() -- %n is not a recognized format. You can see the acceptable formats at the sprintf() manual page.
In short, I suspect you are using the wrong column in your SELECT statement, and that it is actually supposed to be something like username.