user7624275
user7624275

Reputation:

Why does mysqli_num_rows always return 0?

I want to check the input of the user after he hits the submit button if the word exist in the database.

Hence, I have this code. However, it always says Data does not exist in which it finds the condition false.

What is wrong with my code below?

$input_word = trim($_POST["word"]);
$data_check = "SELECT * FROM word_collections WHERE single_word = '$input_word'";
$a = mysqli_query($data_check);
if (mysqli_num_rows($a) == 1)
{
    echo "Data exist.";
}
else
{
    echo "Data DOES NOT exist";
}

Upvotes: 1

Views: 1258

Answers (3)

Naveed Ramzan
Naveed Ramzan

Reputation: 3593

Best way to do this.

$dbhost = 'localhost';
$dbuser = 'username';
$dbuser = 'password';
$dbpass = 'dbname';
$dbConn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

$query = "SELECT * FROM word_collections WHERE single_word = '$input_word'";

$result = $dbConn->query($query);
if($result->num_rows == 1){
    echo "have some records";
}else{
    echo "No records";
}

Upvotes: 0

d3no
d3no

Reputation: 121

$input_word = trim($_POST["word"]);
    $data_check = "SELECT * FROM word_collections WHERE single_word = '$input_word'";
                        $con = mysqli_connect("host",'id','pass','dbname'); // add this connection
                        $a = mysqli_query($con,$data_check);
                        if (mysqli_num_rows($a) == 1)
                        {
                            echo "Data exist.";
                        }
                        else
                        {
                            echo "Data DOES NOT exist";
                        }

You need to put your connection in mysqli_query parameter 1. You may refer tutorial from w3schools .

Upvotes: 0

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Your query failed because you didn't pass db connection to:

$a = mysqli_query($data_check);

The variable for the connection is unknown, so you need to base yourself on:

$a = mysqli_query($connection, $data_check);

and you may have to use >0 instead of ==1 for your num_rows() as there could be more than one record.

Your code is also open to an sql injection; use a prepared statement.

Use PHP's error reporting and mysqli_error($connection) on the query.

Also make sure that your connection is in fact mysqli_ and not another api.

Upvotes: 5

Related Questions