I'm having a hard time identifying the cause of the problem of my code, which is, it won't query on the "UPDATE" part but the "SELECT" part does work. when i tried using the print_r function, it gives an errors/warnings namely:
"Warning: mysqli_query(): Couldn't fetch mysqli"** and **"Warning:
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null
given"
if(!isset($_POST['n_pass'])&&!isset($_POST['n_pass'])){
if(!isset($_POST['password'])||$_POST['password']==""){
echo 'enter current password';
die;
} else {
include 'include/database.php';
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn,$_POST['lname']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$username = mysqli_real_escape_string($conn,$_POST['uname']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
//Check if the password is equal to the password inside database
$sql = "SELECT password FROM users where id = $id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$cpass = $row['password'];
$verify_pass = password_verify($password,$cpass); //check if current password is equal to the existing password
if($verify_pass != 1){
echo 'incorrect password';
die;
} else {
**//Update Data
$sql="UPDATE users SET firstname=$fname, lastname=$lname, email=$email, username=$username where id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
die;
header("Location: profile.php?successfullyupdated");
}
}
}
Your query is missing the quotes around the strings:
$sql="UPDATE users SET firstname='$fname', lastname='$lname', email='$email', username='$username' where id=$id";
You can skip only the id field since it is an Integer.
Sidenote: you are wide open to SQL Injections. You should use prepared statements.
There are plenty of resources on google to start with this topic
Finally, note that
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
is completely useless since you are not returning anything from the UPDATE query.
You can do:
if(mysqli_query($conn, $sql)){
//query was successful - run your code here for success
}else{
//query failed - run your code here for fail
}
Related
Hey guys I'm working on a login/register for and I'm struggeling with the following things. When registering there's a message (registration complete) but there's also an error I can't get rid off.
Als when the username is already taken there should be a message that says that but there isn't. The error I get is the following.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool
given in C:\xampp\htdocs\test\registration.php on line 16
The code I use in registration.php is
<?php
session_start();
$con = mysqli_connect('127.0.0.1','jstam','12345');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = "select * from usertable where name = 'name' && passoword = '$pass'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Gebruikersnaam in gebruik";
}else{
$reg= "insert into usertable (name , password) values ('$name' , '$pass')";
mysqli_query($con, $reg);
echo"Registratie succevol";
}
?>
I believe you may have a typo in your code
$s = "select * from usertable where name = 'name' && passoword = '$pass'";
I assume that passoword should be password. Also, name should be $name
$s = "select * from usertable where name = '$name' && password = '$pass'";
As others have suggested, your code is vulnerable to SQL injection and should NOT be used in production.
This mysqli_fetch_array not returning values. Checked it for SQL errors, none found. some error in PHP or functions I guess. Please help me correct it.
$login = login($username, $password);
if ($login == false) {
$errors[] = "That username and password combination is incorrect";
}
// validate login
function login($username, $password){
$user_id = id_from_username($username);
echo $user_id;
$password = md5($password);
$username = sanitize($username);
$query = "SELECT `password` FROM `user_data` WHERE `username` = '$username' ";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
if ($row[0] == $password) {
echo "Login successful";
return $user_id;
}
else{
echo "Login not successful";
return false;
}
}
// user id from username
function id_from_username($username){
$username = sanitize($username);
$query = "SELECT `user_id` FROM `user_data` WHERE `username` = '$username'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
return $row[0];
}
EDIT: As Lawrence correctly pointed out I missed the variable scope issue. mysqli_query does not have access to $conn variable.
Try to check the number of returned rows in the $result:
echo $result->num_rows;
Or print it to the log if you have some. Not sure how you are checking mysqli_fetch_array does not return values - try var_dump() or print_r().
Few further recommendations:
Both queries in your question select from the same table - user_data - it is pretty inefficient to do it separately (unless id_from_username is commonly used elsewhere), I'd merge that into one query to select it at once:
SELECT user_id, password FROM user_data WHERE ...
Using mysqli_query and concatenating user input into the query is usually a bad idea. Not sure what your sanitize function does but I'd still use variable binding instead, even mysqli supports that with mysqli_prepare, see here.
Based on your code you are storing passwords in database using md5. This is a very bad practice. PHP provides very nice functions password_hash and password_verify since PHP 5.5.0, they will handle password hashing for you and make your application a lot more secure.
I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement
Basically I am having issues with hashing and getting the password verified, and I was hoping someone could help me out by proof reading some of the code.
Below is the registration (php code):
include '../includes/connection.php';
$userID = $_POST['userID'];
$userName = $_POST['userName'];
$Pass = $_POST['password'];
$encrypted_password = password_hash($Pass, PASSWORD_DEFAULT);
if(!empty($userName) && !empty($Pass) && !empty($userID)){
$records = "SELECT * FROM Admins WHERE ID='$userID' OR Username='$userName' OR Password='$encrypted_password'";
$results = mysqli_query($connect,$records);
if ($results->num_rows == 1){
$message = "You have already requested an account.";
echo "<script type='text/javascript'>alert('$message');</script>";
}else{
$query = "INSERT INTO Admins (`ID`,`Username`,`Password`,`AdminLevel`) VALUES ('$userID','$userName','$encrypted_password','0')";
$run = mysqli_query($connect,$query);
$message = "Your request has been submitted.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
Below is the login (php code)
if(!empty($userName) && !empty($Pass)){
$sql = "SELECT * FROM Admins WHERE Username='$userName'";
$sqlr = mysqli_query($connect,$sql);
$sqlrow = $sqlr->fetch_assoc();
$dbPass = $sqlrow['Password'];
$hash = password_verify($Pass, $dbPass);
if ($hash == 0){
die("There was no password found matching what you have entered.");
}else{
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$hash'";
$results = mysqli_query($connect,$records);
if ($results->num_rows == 1){
$row = $results->fetch_assoc();
$_SESSION['user_id'] = $row['ID'];
$_SESSION['admin_level'] = $row['AdminLevel'];
$_SESSION['user_name'] = $row['Username'];
$easyName = $_SESSION['user_name'];
$recordsS = "UPDATE `Admins` SET Status='1' WHERE Username='$userName'";
$resultsS = mysqli_query($connect,$recordsS);
header("Location: index.php");
}else{
die("Sorry... you have entered incorrect login information.");
}
}
}
This is the database heading: https://gyazo.com/69380c5cd0df0259d31799b71f33ce47
When I test this on the website and I login with correct information, "Sorry... you have entered incorrect login information." is echoed.
If I login with false information, "There was no password found matching what you have entered." is echoed.
Why can it detect the password, but not properly execute the else statement in the login section?
Your $records query is failing because you are selecting Password='$hash'" where $hash is either true, or false. The query should have this condition: Password='$dbPass'"
Just as a gut check: The important thing to note is the password field in the database should be huge. The password_hash() can generate some very lengthy text (the current default is 60 characters), so making the field larger will allow for the length needed. Secondly the PHP team is adding more algorithms to the method which means the hash can and will grow. We also do not want to limit our user's ability to use the password or passphrase of their choice. It's best to leave room for the changes.
One more thing: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You have a small mistake in the Query:
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$hash'";
You are matching password against a boolean by mistake. It should be:
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$dbPass'";
You need to hash the $Pass variable for this match. The function password_verify returns a boolean after making the match but the actual hash is done inside the method.
I'm new to mysql and php.
Been working on creating a database with a table for users.
I've managed to successfully add users to the database, and their passwords with md5(yea i know it's not secure), it's not going to be launched online.
My problem is, how do I log a user in, based on their correct username and password.
here is my code
My logic is taht after the query runs, it will return either true or false.
If true, then display successful login, else unsuccessful.
however, even if i input a correct username and password, i still get a unsuccessful login message
i checked the mysql database, and the uesrname is in there correctly
ideas?
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result == true) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
I'm not entirely sure your SQL will run, but just to be on the safe side.
Change it so that
$password_hash = md5($password);
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = '$password_hash'";
And for your original question
if(mysql_num_rows($result) == 1) { //If the SQL returns one row, that means that a user was found with `userName = $username` and `password = md5($password)`
// Login
} else {
// Authentication Failed
}
Also, consider using MySQLi instead of MySQL since it has been depreciated.
First of all, protect your code against SQL injections.
Then, make sure that the password in the DB is really hashed with md5() function.
Make sure you form uses POST method to pass the data to the script.
Try the following code:
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '". addslashes($username) ."' AND password = '". md5('$password')."'";
$result = mysql_query($sql);
if (mysql_num_rows($result)>0) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
mysql_query doesn't return TRUE or FALSE. Per the docs (http://php.net/manual/en/function.mysql-query.php), it returns a resource if successful, or FALSE if there is an error. You need to evaluate the resource to see if it's valid.
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result && $row = mysql_fetch_assoc($result)) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
As mentioned in my comment, the issue seems to be your sql string. Instead of hashing, you are putting the method into the string. So change
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
to
$sql = "SELECT * FROM `users` WHERE userName ='$username' AND password = '".md5('$password')."'";
Your result will not be true or false, but since php treats any value not a 0 as true, it will work as is.
Also, it is strongly recommended to escape all data going into your sql string to prevent sql injection. Another note: mysql is being deprecated, so now would be a great time to move to something like mysqli.