简体   繁体   中英

Mysqli query returns no rows

For whatever reason, I keep getting the echo "No News."; even though I clearly have information put into the table which is named news .

<?php
session_start();
define('DB_SERVER', "localhost");
define('DB_USER', "USERNAME");
define('DB_PASSWORD', "PASSWORD");
define('DB_DATABASE', "DATABASE");


$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// Check connection
if(mysqli_connect_errno()) {
    echo "Email Owner@OtherTXT.com";
    exit();
}

/* create a prepared statement */

$query = "SELECT `title`, `message`, `date` FROM `news`";

$result = $mysqli->query($query);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<h2>";
        echo ($row["title"]);
        echo "</h2>";
        echo "<h3>";
        echo ($row["date"]);
        echo "</h3>";
        echo "<br />";
        echo "<p>";
        echo ($row["message"]);
        echo "</p>";

    }
} else {
    echo "No News.";
}


$mysqli->close();
?>

This is a picture of my table

http://i.imgur.com/7xZTSvd.png

Hope this will help ;)

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<h2>";
        echo ($row["title"]);
        echo "</h2>";
        echo "<h3>";
        echo ($row["date"]);
        echo "</h3>";
        echo "<br />";
        echo "<p>";
        echo ($row["message"]);
        echo "</p>";

    }
} else {
    echo "No News.";
}

Maybe adding a store_result before calling the num rows do the trick:

$result = $mysqli->query($query);

$result->store_result();

if ($result->num_rows > 0) {
...

Or you can put it into the query:

$result = $mysqli->query($query,MYSQLI_STORE_RESULT);

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