I have a MySQL code and I am facing a crisis in 'mysqli_num_rows() expects parameter 1 to be mysqli_result, string given'

2016-11-22 php mysqli

This is my code. The connection code and the login page.

<?php 
    ini_set("display_errors",1);
    class connection //create a class for make connection
    {
    var $host = "localhost";
    var $username = "root";
    var $password = "";
    var $database = "myDb";
    var $myconn;
    var $select;
    var $query;
    function database() //create a function for connect to database
    {
        $conn = mysqli_connect($this->host,$this->username,$this->password);

        if(!$conn) // testing the connection
        {
            die ("Cannot connect to the database");
        }
        else
        {
            $this->myconn = $conn;
        }
        mysqli_select_db($this->myconn,$this->database); //use php inbuil function for select database

        if(mysqli_error($this->myconn)) //if error occured display the error message\\
        {
            echo "Cannot find the database " . $this->database;
        }
        return $this->myconn;
    }
    function query($select)
    {
        $this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
    }
    function fetchQuery()
    {
        return mysqli_fetch_array($this->query);
    }
    function closeConnection() //close the connection
    {
        mysqli_close($this->myconn);
    }
}
?>

And a page where I am handling it.

<?php
$connection = new connection();
$connection->database();
if(isset($_POST['submit']))
{
    $user = $_POST['name'];
    $pass = $_POST['password'];
    $select = "SELECT * From tab_user where txt_uname ='$user' and txt_pass ='$pass' ";
    $result = $connection->query($select); 
    $count = mysqli_num_rows($result);
    if($count>0)
    {
        $row = $connection->fetchQuery();
        $name = $row['txt_full_name'];
        echo $name;
        $connection->closeConnection();
    }
    else
    {
        echo 'Wrong Inputs.';

    }
}
?>

<form method="post">
    <input type="text" name="name">
    <input type="password" name="password">
    <input type="submit" name="submit" value="submit">
</form>

I am facing a problem

mysqli_num_rows() expects parameter 1 to be mysqli_result, string given

How can I solve it?

Answers

Try this

'.$user.' and '.$pass.'

instead of

'$user' and '$pass'

Your query() function does not return anything, but you are trying to work with the return value:

// In code:
$result = $connection->query($select); 
$count = mysqli_num_rows($result);
// In class:
function query($select)
    {
        $this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
    }

You could do the following:

mysqli_num_rows($connection->query);

Or return the result as well as storing it:

function query($select)
    {
        return $this->query= mysqli_query($this->myconn,$select)or die(mysqli_error($this->myconn));
    }

Related