[PHP + MySQL]Database SELECT query returning no re

2019-03-01 06:05发布

问题:

I am trying to access my database to get some data, but it keeps returning with the following errors.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\default.php on line 84

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\default.php on line 86

I have checked the connection and the code is inputting data properly, it's just the results query that won't return any values. Personally, I can't see where the error is because other queries, such as INSERT and CREATE are working perfectly.

<?php
    mysqli_select_db($conn, $dbName);
    $sql = "SELECT * FROM tbl_users WHERE id = 1;";
    $result = mysqli_query($conn, $sql);
    echo mysqli_num_rows($result); //Line 84

    if (mysqli_num_rows($result) > 0) { //Line 86
        while($row = mysqli_fetch_assoc($result)) {
            ...
        }
    } else {
        echo "0 results";
    }
?>

If you require any further information, please ask me and I will attempt to provide it.

Full code:

//**Create Connection**//
$conn = mysqli_connect($serverName, $username, $password);

//**Check Connection**//
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
else { echo "<p>Connected successfully!</p>"; }



//**Create Database**//
$dbName = "myDB";
$sql = "CREATE DATABASE IF NOT EXISTS " . $dbName . " CHARACTER SET utf8 COLLATE utf8_general_ci;";

//Error Handling
if (!mysqli_query($conn, $sql)) { echo "Error creating database: " . mysqli_error($conn); }
else { echo "<p>Database created successfully!</p>"; }

//**Create Table**//
mysqli_select_db($conn, $dbName);
$tbl_name = "tbl_users";
$sql = "CREATE TABLE IF NOT EXISTS " . $tbl_name . " (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(64) NOT NULL, lastName VARCHAR(64) NOT NULL, userEmail VARCHAR(256) NOT NULL, reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8 COLLATE utf8_general_ci;";

//Error Handling
if (!mysqli_query($conn, $sql)) { echo "Error creating table: " . mysqli_error($conn); }
else { echo "<p>Table '" . $tbl_name . "' created successfully!</p>"; }

mysqli_select_db($conn, $dbName);
$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

if (!$result = mysqli_query($conn, $sql)) {
printf("Errormessage: %s\n", mysqli_error($conn));
}

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo $row . "<br>";
    }
} else {
    echo "0 results";
}

回答1:

Your code is ok. Try to execute that SQL query in database ...



回答2:

you aren't showing us all of your code.

You have 2 simultaneous calls and you get the error reported



回答3:

The problem is here:

You're using mysqli_query() twice in this piece of code:

$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

if (!$result = mysqli_query($conn, $sql)) {
printf("Errormessage: %s\n", mysqli_error($conn));
}

You need to remove one and do:

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}

while adding an escape route else{...} and affected_rows() also.

  • Which is the reason why your query is failing.

Edit:

This, you're using $conn twice and not using a variable reference for your query:

mysqli_select_db($conn, $dbName);
$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

Change it to and using the 4 parameters scheme of mysqli_connect(), since the DB has already been created at this point: (assuming the id of "1" has already been created above that).

$dbName = "myDB";
$conn = mysqli_connect($serverName, $username, $password, $dbName);

$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
else{ echo "Success"; }

or by removing or die(mysqli_error($conn)) and getting the error passed on after, if any.

$dbName = "myDB";
$conn = mysqli_connect($serverName, $username, $password, $dbName);

$sql = "SELECT * FROM tbl_users WHERE id = 1";
$result = mysqli_query($conn, $sql);

if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
else{ echo "Success"; }

(additional edit)

You could also try this method and used in conjunction with what I already stated above:

$numrows = mysqli_num_rows($result);

if($numrows > 0){
// do something
}

Add error reporting to the top of your file(s) which will help find errors.

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

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.



回答4:

use mysqli_error(); to see where the problem is

    mysqli_free_result($result);
    if (!$result = mysqli_query($conn, $sql)) {
        printf("Errormessage: %s\n", mysqli_error($conn));
   }

if your answer is "Errormessage: Commands out of sync; you can't run this command now" then i think your problem is that you are still connected in an different query add mysqli_free_result($result); before above code to see real error.



回答5:

I don't think, there is anything wrong with your code but there are some issues with your programming style. You should try this out

   $conn = mysqli_connect('host', 'username', 'password', 'database', '[option port number]') or die('<h1>Error connecting to database server</h1>'); 

    //=> the optional port number defaults to 3306 - recommended if your database is hosted on a live server else leave blank 

    if ($conn) {

    $query = "SELECT * FROM `tbl_users` WHERE `id` = 1"; 

        //if id is unique this should just be a single row from your database 

    $result = $mysqli_query($dbc, $query) or die("Invalid query sytax" . mysqli_error($conn));

        if($result){

            echo "The number of rows are(is) " . mysqli_num_rows($result);

                while($row = mysqli_fetch_assoc($result)) {

                    //do stuff here  or remove while loop and var_dump() 
                }
        } else {

            echo "No record found"; 
        }
    }