PHP Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in

<?php
include("header.php");
$_SESSION['loc'] = "viewkeyowners.php";
if ($_SESSION['loggedin'] <> 1)
{
    header("Location: logintest.php");
    exit();
}

//this is done because if user closes a tab/page, and logs back in(still in session), it would redirect to the last opened tab/page
function onclose(){
    unset($_SESSION['loc']);
}

register_shutdown_function('onclose');

if(isset($_SESSION['illegalmove'])){
    if($_SESSION['illegalmove'] == 1){
        echo "<script>alert('Your account is not authorized to view this page.');</script>";
        $_SESSION['illegalmove'] = 0;
    }
}
if(isset($_POST['checking_viewbtn']))
{
    $id = $_POST['id'];
    // echo $return = $id;

    $query = "SELECT * FROM keyOwners WHERE id='$id' ";
    $query_run = mysqli_query($conn, $query);

    if(mysqli_num_rows($query_run) > 0)
    {
        foreach($query_run as $row)
        {
            echo $return = '                                
                                <h5> Key Type : '.$row['keyType'].'</h5>
                                <h5> Key Department : '.$row['area'].'</h5>
                                <h5> Key Description : '.$row['keyDesc'].'</h5>
                                <h5> Key Status : '.$row['keyStatus'].'</h5>
                <h5> First Name : '.$row['fname'].'</h5>
                <h5> Last Name : '.$row['lname'].'</h5>
                <h5> Employee Status : '.$row['emplStatus'].'</h5>
                <h5> Employee Number : '.$row['emplNum'].'</h5>
                                <h5> Date Assigned : '.$row['dateAssigned'].'</h5>
                                <h5> Updated By : '.$row['userid'].'</h5>


            ';
        }
    }
    else
    {
        echo $return = "<h5>No Record Found</h5>";
    }

}
?>

Recommended Answers

All 2 Replies

Where do you initialize/open your connection in $conn ?

Where is your:

$conn = mysqli_connect(...);

Is it inside header.php?

Currently, mysqli_query() on line 29 is failing. On line 28, before running the query, try temporarily adding this debugging code:

// Check connection 
if (mysqli_connect_errno($conn)) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
}

That will spit out an error message if there's something wrong with the connection.

Something else that could be a reason mysqli_query() is failing is because your $query isn't escaped. For example, if the value retrieved from POST for id is: Foo' then that will result in ... WHERE id = 'Foo'' which is invalid. Instead, replace line 28 with:

$query = "SELECT * FROM keyOwners WHERE id=" . mysqli_real_escape_string($conn, $id);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.