Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean - php

Attempting to create a 'Change Password' page for my website, I keep being confronted with these two errors and I can't seem to understand why they are appearing;
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/ll12rth/public_html/COMM2735/database/password.php on line 51
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /home/ll12rth/public_html/COMM2735/database/password.php on line 139
<?php
session_start();
$db_hostname = 'localhost';
$db_database = "****"; //replace with your db name
$db_username = "****"; //replace with the db username that you created
$db_password = "****"; //replace with the db password that you created
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if (!$db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
} else
require_once('checklog.php');
require_once("functions.php");
// Grab the form data
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$newpassword = trim($_POST['newpassword']);
$repeatpassword = trim($_POST['repeatpassword']);
if (isset($_POST['submit'])) {
if ($username && $password) {
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)) {
$db_username = $row['username'];
$db_password = $row['password'];
if ($username == $db_username && salt($password) == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['logged'] = "logged";
// header('Location: home.php');
// PASSWORD CHANGING IS DONE HERE
if ($newpassword == $repeatpassword) {
//From register
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
} else {
//part 8
// Process details here
//include file to do db connect
if ($db_server) {
//clean the input now that we have a db connection
$newpassword = clean_string($db_server, $newpassword);
$repeatpassword = clean_string($db_server, $repeatpassword);
mysqli_select_db($db_server, $db_database);
// check whether username exists
$query = "SELECT password FROM users WHERE password='$newpassword'";
$result=mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "This is your current password. Please try again.";
} else {
//part 9
// Process further here
$newpassword = salt($newpassword);
$query = "INSERT INTO users (password) VALUES
('$password')";
mysqli_query($db_server, $query) or die("Insert failed. " . mysqli_error($db_server));
$message = "<h1>Your password has been changed!</h1>";
}
mysqli_free_result($result);
} else {
$message = "Error: could not connect to the database.";
}
require_once("php/db_close.php"); //include file to do db close
}
}
//This code appears if passwords dont match
else {
$message = "<h1>Your new passwords do not match! Try again.</h1>";
}
} else {
$message = "<h1>Incorrect password!</h1>";
}
} else {
$message = "<h1>That user does not exist!</h1>" . "Please <a href='password.php'>try again</a>";
}
mysqli_free_result($result);
//Close connection!
mysqli_close($db_server);
} else {
$message = "<h1>Please enter a valid username/password</h1>";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Techothing password</title>
<div class="aboutcontainer">
<h1>What do you want to change your password to <?php
echo $_SESSION['username'];
?>?</h1>
<form action='password.php' method='POST'>
Current Username: <input type='text' name='username'><br />
Current Password: <input type='password' name='password'><br />
New Password: <input type='password' name='newpassword'><br />
Repeat New Password: <input type='password' name='repeatpassword'><br />
<input type='submit' name='submit' value='Confirm'>
<input name='reset' type='reset' value='Reset'>
</form>
<?php
echo $message
?>
<br />
</div>
</div>
</div>
</div>
</body>
</html>
</body>
</html>

This line
$result = mysqli_query($db_server, $query);
returns either a result object, or, if the query fails for some reason, returns false.
Most people developing this kind of code, especially when we're new to it, check these errors. You could do that roughly like this.
if ( false === $result ) {
printf("Errormessage: %s\n", msqli_error($db_server));
}

Related

having trouble with PHP and SQL

I am trying to display an error message in php ( $error="Username or Password is invalid";
) when the username or password is not in the database. But without even running the code(clicking login in index.php the error message is displaying. Thanks :)
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
}
if (isset($_POST['submit'])) {
// Define $username and $password
$name=$_POST['username'];
$pass=$_POST['password'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
if($name==$row["username"] && $pass== $row["password"]){
header("location: profile.php"); // Redirecting To Other Page
}else{
$error="Username or Password is invalid";
}
}
}
else {
echo "Server is down";
}
$conn->close();
}
?>
My index.php
<?php
include('../php/login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
I updated your security a little. Make sure you always validate user input. The code below is secure against SQL injections. No way of injection possible! Also HEX attacks are not possible.
<?php
if (!isset($_SESSION)) { session_start(); }
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "company";
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errmessage = $error = '';
function checkUsername($data) {
if (preg_match('/[^A-Za-z0-9.]{8,50}/', $data)) { // A-Z, a-z, 0-9, . (dot), min-length: 8, max-length: 50
$data = false;
}
return $data;
}
function checkPassword($data) {
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,50}$/', $data)) { // A-Z, a-z, 0-9, !, #, #, $, %, min-length: 8, max-length: 50
$data = false;
}
return $data;
}
if (isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (checkUsername($username) === false) {
$error = "Username is not valid!";
exit();
}
if (checkPassword($password) === false) {
$error = "Password is not valid!";
exit();
}
$secure_name = bin2hex(htmlspecialchars($username));
//$secure_pass = hashpassword($securepass); // Hash your passwords!
$secure_pass = bin2hex(htmlspecialchars($password));
$sql = "SELECT * FROM login WHERE username = UNHEX('$username') AND password = UNHEX('$password')";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
session_regenerate_id();
$_SESSION['login_user'] = true;
header("location: profile.php");
} else {
$error = "Username and/or Password is invalid";
}
$conn->close();
} else {
echo "Error";
}
?>
Source for HEX against injection: How can I prevent SQL injection in PHP? (Zaffy's answer)
Extra information:
Do not check only if the session login exist, but check also its value!
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
Must be
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] === true){
header("location: ../php/profile.php");
exit();
} else {
// Loginscript
}
The PHP script seems to take ALL username/password pairs from DB
$sql = "SELECT id, username, password FROM login";
Later in while loop first pair not matching with user input would trigger an error message assignment

What 's wrong for opening my new page?

I tried to create a login page in PHP. I have a problem with opening the new page when the username and password are correct.
All the pages are in the same directory, which is Inventory.
Here is the code:
<?
$serverName ="localhost";
$dbname="inventory";
$conn = mysql_connect($serverName,"root","");
if(!$conn) die("Connection error". mysql_connect_error());
else echo "connected successfully";
if(isset($_POST['login'])){
if(empty($_POST['username']) || empty($_POST['password']))
echo "<script>
alert('يجب إدخال إسم المستخدم و كلمة السر';);
</script>";
else
{
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db($dbname,$conn) or die("database connection error" . mysql_error());
$query = mysql_query("select * from users where username = '$username' AND password = '$password'", $conn);
$name = mysql_query("select name from users where username = '$username' AND password = '$password'", $conn);
$rows = mysql_num_rows($query);
if($rows == 1)
{
//echo $username.'<br>';
//echo $password.'<br>';
//echo '<br>'. "correct user name and password";
$_SESSION['name'] = $name;
header("location: C:\xampp\htdocs\inventory\menu.php");
//echo "<script> window.open('C:/xampp/htdocs/inventory/menu.php','_self'); </script>";
}
else
{
//echo '<br>'. "incorrect user name and password";
echo "<script>
alert('اسم المستخدم أو كلمة السر غير صحيحة');
</script>
";}}}
mysql_close($conn);
?>
Any suggestions about what might be wrong?

Issue with logging in with mySQL and PHP

Im trying to allow users that are on the database to log in if their credentials are present, problem is, whenever I enter details into the login screen, it will always return Invalid Login Credentials, regardless of whether or not the name/password is on the database.
Here is what I'm working with:
loginSubmit.php
<?php
//begin our session
session_start();
//Check the username and password have been submitted
if(!isset( $_POST['Username'], $_POST['Password']))
{
$message = 'Please enter a valid username and password';
}
else
{
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$query = "SELECT * FROM
customers WHERE name =
('$_POST[Username]' AND password = '$_POST[Password]')";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $username;
}
else
{
echo "Invalid Login Credentials";
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
echo "Hello " . $username;
}
}
catch(Exception $e)
{
$message = 'We are unable to process your request. Please try again later"';
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Here</h2>
<form action="loginSubmit.php" method="post">
<fieldset>
<p> <label for="Username">Username</label>
<input type="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</form>
</body>
</html>
AddUser
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (name, password)
VALUES
('$_POST[Username]','$_POST[Password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
//Unset the form token session variable
unset( $_SESSION['formToken'] );
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
if($ex->getCode() == 23000)
{
$message = 'Username already exists';
}
else
{
$message = 'We are unable to process your request. Please try again later"';
}
It might be because of this, the way you have the brackets.
-Please see my notes about using prepared statements and password_hash() below.
SELECT * FROM customers
WHERE name = ('$_POST[Username]'
AND password = '$_POST[Password]')
Change it to:
SELECT * FROM customers
WHERE name = '$username'
AND password = '$password'
and for testing purposes, try removing
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
that could be affecting / rejecting characters. Make sure there is no white space also.
Also changing if($count == 1) to if($count > 0)
or replacing $count = mysql_num_rows($result); if($count == 1) { with if(mysql_num_rows($result) > 0){
Your password is not being hashed
After testing your Adduser code, I noticed is that your hashed password isn't being stored as a hash.
Change ('$_POST[Username]','$_POST[Password]') in your Adduser page to ('$username','$password').
I suggest you move to mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, your present code is open to SQL injection.
Here is a good site using PDO with prepared statements and password_hash().
http://daveismyname.com/login-and-registration-system-with-php-bp
See also:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Try this mate
$query = "select * from customer where name = '" .$username ."' and password = '" .$password ."'";
//use the SANITIZED data
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row) {
$_SESSION['name'] = $row['name'];
$_SESSION['password'] = $row['password'];
}
else { //not found
header('Location: go back.php?error=2');
}
echo "Hello " . $username;

Offset 0 is invalid for MySQL result index 10 , cannot retrieve data from mysql php

In the script, no matter I input a right or a wrong user name, the result remains the same.
It is like this:
{"success":1,"message":"Login successfully!","user":{"customerID":null,"firstname":null,"lastname":null,"address":null,"postcode":null,"phone":null}}
I tried to use mysql_data_seek() and it returns Offset 0 is invalid for MySQL result index 10.
I guess there is nothing fetched by mysql_query().
Could anyone help me to solve this problem?
<?PHP
$username = "";
$password = "";
$re = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$username = htmlspecialchars($username);
$password = htmlspecialchars($password);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$dbusername = "";
$dbpassword = "";
$host = "";
$dbname = "";
$db_handle = mysql_connect($host, $dbusername, $dbpassword);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$username = quote_smart($username, $db_handle);
$password = quote_smart($password, $db_handle);
$query = "SELECT * FROM Customer WHERE username = $username AND password = md5($password)";
$info = mysql_query($query);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($info) {
$user = mysql_fetch_array( $info );
echo $user['firstname'];
$re["success"]=1;
$re["message"] = "Login successfully!";
//add parameters that will return to android
$re["user"]["customerID"]=$user['customerID'];
$re["user"]["firstname"]=$user['firstname'];
$re["user"]["lastname"] = $user['lastname'];
$re["user"]["address"]=$user['address'];
$re["user"]["postcode"]=$user['postcode'];
$re["user"]["phone"]=$user['phone'];
$re= json_encode($re);
echo $re;
session_start();
$_SESSION['login'] = "1";
$_SESSION["re"]=$re;
//header ("Location: userdata.php");
}
else {
$re["success"]=0;
$re["message"] = "User Not Found";
$re = json_encode($re);
echo $re;
}
}
else {
$re["success"]=0;
$re["message"] = "Can not connect to database";
$re= json_encode($re);
echo $re;
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="Customer Login" METHOD ="POST" ACTION ="login.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $username;?>" maxlength="45">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $password;?>" maxlength="45">
<P align = center>
<INPUT TYPE = "Submit" Name = "Submit" VALUE = "Login">
</P>
</FORM>
</body>
</html>
Can you try this, added rows count check mysql_num_rows($info);
$query = "SELECT * FROM Customer WHERE username = '".$username."' AND password = '".md5($password)."' ";
$info = mysql_query($query) or die("MySQL ERROR: ".mysql_error());
$count = mysql_num_rows($info); // added rows count check
if($count>0){
$user = mysql_fetch_array( $info );
echo $user['firstname'];
$re["success"]=1;
$re["message"] = "Login successfully!";
//add parameters that will return to android
$re["user"]["customerID"]=$user['customerID'];
$re["user"]["firstname"]=$user['firstname'];
$re["user"]["lastname"] = $user['lastname'];
$re["user"]["address"]=$user['address'];
$re["user"]["postcode"]=$user['postcode'];
$re["user"]["phone"]=$user['phone'];
session_start();
$_SESSION['login'] = "1";
$_SESSION["re"]=$re;
//header ("Location: userdata.php");
$re= json_encode($re);
echo $re;
}
else {
$re["success"]=0;
$re["message"] = "User Not Found";
$re = json_encode($re);
echo $re;
}
Note: Use mysqli_* function instead of mysql_* functions (deprecated)
You need to check if any row returns or not.
also session_start() must be at the top of file
session_start();
$query = "SELECT * FROM Customer WHERE username = $username AND password = md5($password) LIMIT 1";
$info = mysql_query($query);
$found = mysql_num_rows($info);
if($found!=0)
{
$user = mysql_fetch_array( $info );
echo $user['firstname'];
$re["success"]=1;
$re["message"] = "Login successfully!";
//add parameters that will return to android
$re["user"]["customerID"]=$user['customerID'];
$re["user"]["firstname"]=$user['firstname'];
$re["user"]["lastname"] = $user['lastname'];
$re["user"]["address"]=$user['address'];
$re["user"]["postcode"]=$user['postcode'];
$re["user"]["phone"]=$user['phone'];
$re= json_encode($re);
echo $re;
$_SESSION['login'] = "1";
$_SESSION["re"]=$re;
//header ("Location: userdata.php");
}
NOTE: mysql_* functions are deprecated. move on mysqli_* functions asap
if the result set is empty mysql_data_seek() will fail with a E_WARNING. That is I think happening in you case because you are not checking whether the result set is empty or not before calling the mysql_data_seek().
Always check the result for number of rows if they are >=1 then you are safe to call mysql_data_seek()

Why won't the data be stored in my database? Error saying "You have an error in your SQL syntax;..."

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. Also every time I register at the moment it comes up with error "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 'testing101''' at line 1." Can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = '".$uname."'";
$result = mysql_query($SQL)or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You're double-quoting your text:
1 set of quotes gets added in your smart_quote() function.
1 set of quotes gets added in your actual query, so you're producting:
INSERT .... VALUES (''$uname'', ''$password'');
If you had proper error handling your query calls, you'd have seen this:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^

Categories