简体   繁体   中英

Same mysqli query but different result while using with php

I have two php scripts to access data from my database table.

index.php

<?php
require "init.php";
$name = "Jack";
$user_query = "SELECT * FROM employee WHERE employeeName like '$name';";
$result = mysqli_query($con,$user_query);

$data = array();

$no_of_rows = mysqli_num_rows($result);


if($no_of_rows > 0)
{
    $data["error"] = TRUE;
    $data["message"] = "User Found";
    echo json_encode($data);
}

else
{
    $data["error"] = FALSE;
    $data["message"] = "User Not Found";
    echo json_encode($data);

}
?>

Here if I echo out the $no_of_rows , I get 1 which is correct since I have only one row corresponding to the name Jack.

Here is another approach to access the same data from the same table:

test.php

<?php

require "userTester.php";
$name = "Jack";


$mUser = new UserCheck();

$testResult = $mUser -> userPresent($name);

$data = array();

if($testResult == true)
{
    $data["error"] = TRUE;
    $data["message"] = "User Found";
    echo json_encode($data);
}

else
{
    $data["error"] = FALSE;
    $data["message"] = "User Not Found";
    echo json_encode($data);
}

?>

userTester.php

<?php
require "init.php";

class UserCheck
{

    function userPresent($name)
    {
        echo "Name = " .$name;
        $my_query = "SELECT * FROM employee WHERE employeeName like '$name';";
        $result = mysqli_query($con,$my_query);

        echo json_encode($result);

        $num_of_rows = mysqli_num_rows($result);

        echo "Rows = " .$num_of_rows;

        if($num_of_rows > 0)
        {
            return true;
        }

        else
        {
            return false;
        }

    }

}
?>

In this case, the $num_of_rows always returns 0 . In fact the sql query output is always null.

I am using the same db tables in both cases. I don't understand whats wrong.

Note:- the init.php is used to make the connection to the database and it works fine.

You failed to pass in the $con variable in your method.

You must change the method signature to pass in both the name variable and the connection variable.

You are getting no results because it doesn't have a database connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM