DanMossa
DanMossa

Reputation: 1092

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 [email protected]";
    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

Upvotes: 1

Views: 2133

Answers (2)

Dimas Pante
Dimas Pante

Reputation: 2521

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);

Upvotes: -1

vignesh.D
vignesh.D

Reputation: 776

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.";
}

Upvotes: 2

Related Questions