The numerical row is not being detected within the table

I am currently developing a login system for a news website as part of my coursework. However, I am facing an issue where the if statement using $rows->num_rows == 1 always executes the "else" code. This means that it is not detecting a row in my database table that matches the user information being entered. Below is the PHP code that is triggered when data is submitted through the HTML form:

<?php
error_reporting(E_ALL);  
ini_set('display_errors', 1); 

// Connect to DB
include_once("db_connect.php") or die ("Could not connect to DB");
$username = $_POST['user'];
$password = $_POST['password'];

session_start();

if(trim($username) != '' and trim($password) != ''){

    // Sanitize input
    $username = stripslashes($username);
    $password = stripslashes($password);

    $username = strip_tags($_POST['user']);
    $password = strip_tags($_POST['password']);

    $username = mysqli_real_escape_string($conn, $username);
    $password = mysqli_real_escape_string($conn, $password);

    // Check if username exists        
    $query = mysqli_query($conn, "SELECT * FROM user WHERE users='$username' AND password = '$password'")
    or die(mysqli_error($conn));

    $numrows = mysqli_num_rows($query);

    if($numrows > 0){
        $_SESSION['login_user'] = $username; // Initialize Session
        header("location: index.php"); // Redirect To Another Page
        exit;
    } else {
        echo "Username or password is incorrect.";
    }
} else {
    echo "Please enter information";
}
?>

The issue arises at the end if statement where no rows are detected. The database table contains one row of user information (username & password), and the HTML form uses POST method.

After researching for 3 hours, I still haven't found a solution to this problem.

Current error logs:


Warning: include_once(1): failed to open stream: No such file or directory   in /home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 6

Warning: include_once(): Failed opening '1' for inclusion  
(include_path='.:/usr/share/pear/') in     
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 6

Notice: Undefined variable: conn in     
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 22

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null    
given in /home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line   
22

...

EDIT: Following Fred -ii-'s suggestion,

include_once("db_connect.php")or die ("Couldnt connect to DB");
has been placed at the beginning of the code.

Secondly, a new if statement has replaced the old version, as per Fred -ii-'s advice.

Thirdly, the SQL statement has been corrected since there was confusion between table and column names.

Lastly,

error_reporting(E_ALL); ini_set('display_errors', 1);
has been added to facilitate error identification, also thanks to Fred -ii-'s recommendation.

Answer №1

The following response aligns with the original query you posted at . It appears that the include statement in your code was duplicated without being marked as an edit, causing potential issues.


It seems like you're getting ahead of yourself

include_once("db_connect.php") or die ("Couldn't connect to DB");

This statement should come prior to any functions that require a database connection, such as mysqli_real_escape_string().

Consider implementing if ($rows->num_rows >= 1) or if ($rows->num_rows > 0) to account for scenarios where there might be multiple entries with the same username as your database expands. I encountered a similar situation recently.

Remember to use exit; after each header to prevent unintended code execution.

Error handling for queries is also crucial and seems to be missing in your current implementation.

If problems persist, some functions applied to POST arrays may unintentionally alter valid characters. Consider revising or removing them.

Utilizing a prepared statement can mitigate these issues.

Checking for Errors (in case your query fails).

Refer to these resources: http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php for guidance on error reporting within your code.


Password Security

Noticed that passwords are potentially stored in plain text, which poses security risks.

Consider using one of the following methods:

Note on Column Length:

When transitioning to password_hash() or its compatibility counterpart, ensure your password column length is adequate (recommended minimum of 60 characters). Failure to adjust column length could result in silent failures from MySQL.

Additional resources:


Edit:

You should update this segment: (potential issue with $rows->num_rows)

$query="SELECT * FROM user WHERE users='$username' AND password = '$password'";
$rows = mysqli_query($conn, $query);

if ($rows->num_rows == 1){

    $_SESSION['login_user']=$username; // Initializing Session

    header("location: index.php"); // Redirecting To Other Page
}

to:

$query = mysqli_query($conn, "SELECT * FROM user WHERE users='$username' AND password = '$password' ")
or die(mysqli_error($conn))
;

$numrows=mysqli_num_rows($query);

if($numrows > 0){

// echo "Record exists.";

    $_SESSION['login_user']=$username; // Initializing Session

    header("location: index.php"); // Redirecting To Other Page
    exit;
}

Add the following snippet at the beginning of your file:

<?php 
error_reporting(E_ALL);  
ini_set('display_errors', 1); 

// rest of your code

Note:

Questioning the usage of SELECT * FROM user WHERE users in your query

Verify that the correct table has been selected and no inadvertent errors have occurred.

Answer №2

Here's an alternative code suggestion for you:

Consider using the following snippet:

if ($result = mysqli_fetch_array($rows,MYSQLI_NUM)){

Instead of the previous code:

if ($rows->num_rows == 1){

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with flash installation

I'm currently working on a WordPress website at www.studium.cl. However, I've encountered an issue when trying to open it in Internet Explorer. Each time I try to access the site, a window pops up prompting me to install Adobe Flash Player. Even ...

Is it possible to retrieve information from a MySQL database by utilizing Bootstrap and Ajax with the selected ID?

I am currently working on two php pages. The first php page contains a table with records that can be edited using a Bootstrap Modal, while the second php page processes updates to the MySQL database. Below is the code for the first php page (edit_account ...

Sending a null value through AJAX to a controller

I've been working on adjusting my save routine to pass a null value to id_cellcarrier in my codeigniter controller. The code snippet below showcases what I've attempted so far, but it doesn't seem to be functioning correctly. I'm omitti ...

Increasing the value of a string in PHP

Looking to generate an array of strings that start with a random amount of letters (0 to more than 10) and end with numbers. For example: - S001, S002, ..., S015 - AB67116, AB67117, ..., AB67128 - G07, G08, G09, G10, G11 If given the starting string an ...

Can you help me figure out what's causing issues with my almost finished Sudoku solver?

I'm currently sharpening my algorithm skills by working on a sudoku solver. Please note that it's a work in progress! I still need to implement backtracking for cases where there are multiple possible values for a cell. My current challenge lies ...

Leveraging JSONP, jQuery, and PHP for executing cross-domain AJAX requests

: html: <form id="myform"> <input id="inputfield" name="view"> </form> js: var inputdata = $('#inputfield').val('ocean-view'); $('#myform').submit(function(e) { e.preventDe ...

Searching for the variable value stored in a JSON column of a database using Codeigniter - what's the method

Working with Codeigniter, I am attempting to retrieve a value from the database like this; $this->db->where('json_value','test1'); The issue at hand is that the 'json_value' column looks like = [{"name":" ...

Discovering the Secrets of Laravel 5: Harnessing the Power of Vue.js to Access Data Attribute Values

I'm a beginner in vue js. Within our app, we have implemented validation to check if a value already exists in the database. I would like to enhance this feature by making it dynamic. To achieve this, I have added a data attribute to my field which is ...

In my PHP project, I am working on implementing a feature that will display the name of the logged-in user on the website, such as "Hello Mike" or "Welcome Mike"

When a user is logged into my website, I want it to display a greeting like "Hello" or "Welcome User." This is the code I am currently using: <?php $user = $_GET['session_is_registered']; echo ('$user'); ?> However, the PHP c ...

Using AJAX to call a PHP controller and disabling the layout

The details may not be clear enough, so let me elaborate further. I am trying to specify the ajax URL as www.domain/controller/method. I have successfully implemented this using regular PHP code. However, when attempting to achieve the same result using ...

Issues with Jquery Autocomplete feature when using an Input Box fetched through Ajax requests

When a user selects an option from the drop-down list, an input box is dynamically added to the page using AJAX. document.getElementById("input_box").innerHTML ="<input id='ProjectName'/>"; However, there seems to be an issue with jQuery ...

Select a file and upload an image promptly after it is chosen

Is there a way to automatically upload an image once a user selects a file in their browser? Similar to how it works on Facebook, where users can choose a file for their cover or profile image and then the upload process begins. Currently, all I have is ...

Integrate these scripts for seamless functionality: JavaScript/AJAX and PHP

Currently, I am in the process of learning all the languages involved here and facing a challenge while trying to merge two scripts to perform a single task. The goal is to select a branch from a form option list, transmit that value from the option to a ...

"Using PHP to encode an array into JSON format might result in additional

My PHP array needs to be printed as clean JSON, but I'm encountering issues with extra quotes. While the current JSON output is technically valid, it's not formatted how I want it to be. Below you can see the original PHP array, the json_encode o ...

Safely handling variable table names in MySQL with Codeigniter

Currently, I am encountering a minor issue as I work on an application that necessitates the use of dynamic table names in MySQL. Essentially, my process involves selecting albums from a database based on various factors such as Genre, Play Length, and Re ...

Paginating content without the need for a database

Seeking assistance on implementing pagination for displaying trading history API responses, without utilizing a database. Can anyone provide guidance and help with the necessary logic? Here is an excerpt of my code: <?php error_reporting(E_ALL) ...

The IMG directory cannot be stored in the database but can be viewed using the same variables used in the query

I'm facing an issue while trying to upload an image to my server using a form created by Sanwebe. You can find the form here. After pressing the upload button, the new thumbnail loads perfectly fine. However, for some reason, the image is not being up ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

Looking for the location of the apc.php file?

I've successfully deployed the APC cache on AWS Elastic Beanstalk (confirmed via phpinfo()) How can I verify if APC is functioning properly? Where can I find the location of the apc.php file? Thank you ...

Regular expressions - retrieve all properties of a specific element

I have a string that includes various HTML entities <example type="type 1" id="12345" >Some content</example> <anothertag title="another title" id="67890" attr1="value one" attr2="value two">some text&nbsp; can be inserted&copy;M ...