Mysqli查询不返回任何行

时间:2015-02-06 11:48:43

标签: php mysql mysqli

无论出于何种原因,即使我清楚地将信息放入名为echo "No News.";的表格中,我仍然会收到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();
?>

这是我桌上的照片

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

2 个答案:

答案 0 :(得分:3)

希望这会有所帮助;)

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

答案 1 :(得分:0)

在调用num行之前添加 store_result 可能会有诀窍:

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

$result->store_result();

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

或者您可以将其放入查询中:

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