使用PHP查询数据库并返回结果以显示在网页上

时间:2016-05-30 13:49:15

标签: php html mysql sql database

我试图从数据库中选择一些简单信息并将其显示在网页上。我无法解决为什么如果(以下代码中的$ result-> num_rows> 0)评估为false。其中大部分是直接从W3Schools网站复制而来的:http://www.w3schools.com/php/php_mysql_select.asp 所以它真的不应该有任何问题..

<html>
 <div class="panel"> 
 <!--this should print out atleast something from the database, but it's printing 0 results. -->
<?php include("populate_feature_list.php"); ?>
 </div>
 </html>           

这是包含的PHP文件的内容:     

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$sql = mysql_query($conn,"SELECT name, rating FROM table ORDER BY rating DESC LIMIT 5;");

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Provider: " . $row["name"]. " - Rating: " . $row["rating"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

?>

这是执行查询时在SQL服务器上返回的内容:

    +----------------------+--------+
    | name                 | rating |
    +----------------------+--------+
    | persona              | 4.8000 |
    | personb              | 4.7500 |
    | personc              | 4.6500 |
    | persond              | 4.1500 |
    | persone              | 2.4000 |
    +----------------------+--------+

表格说明:

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| name   | varchar(20) | YES  | UNI | NULL    |       |
| rating | float(8,4)  | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+

1 个答案:

答案 0 :(得分:2)

你在PHP中混合了两个MySQL apis。

$sql = mysql_query($conn,"SELECT name, rating FROM table ORDER BY rating DESC LIMIT 5;");

然后你在mysqli中使用mysql_query调用的返回值:

$result = $conn->query($sql);

这应该是:

$sql = "SELECT name, rating FROM table ORDER BY rating DESC LIMIT 5;";

将来学习这一点的简单方法是查看每个参数所接受的内容。通过查看http://php.net/manual/en/mysqli.query.php,您可以看到$conn->query()接受一个字符串作为第一个参数。