试图在HTML表格中显示MySQL查询的结果

时间:2013-10-17 07:08:40

标签: php mysql

我试图从数据库表中获取一些简单信息并将其发布到HTML页面上。这看起来很简单直接,我没有错误,这意味着我连接到数据库和表。我已经存在所有数据(手动输入)。

我假设这是我调用列名来进行查询的方式。

<?php
    require_once("settings.php");
        //Open Connection
    $conn = @mysqli_connect("$host","$user","$pswd")
        or die ('Failed To Connect to Server');
    @mysqli_select_db("$conn", "$dbnm")
        or die ('Database Not Available');
        //Set up SQL string and excecute
    $car_id = mysqli_escape_string($_GET['car_id']);
    $make = mysqli_escape_string($_GET['make']);
    $model = mysqli_escape_string($_GET['model']);
    $price = mysqli_escape_string($_GET['price']);

    $query = "SELECT car_id, make, model, price FROM cars";

    $results = mysqli_query($conn, $query);

        echo "<table width ='100%' border='1'>
        <tr>
        <th>car_id</th>
        <th>make</th>
        <th>model</th>
        <th>price</th>
        </tr>";

        //  $row = mysqli_fetch_row($query);
                while ($row = mysqli_fetch_array($results)) {
                echo "<tr>";
                echo "<td>" . $row['car_id'] . "</td>";
                echo "<td>" . $row['make'] . "</td>";
                echo "<td>" . $row['model'] . "</td>";
                echo "<td>" . $row['price'] . "</td>";
                echo "</tr>";
        //  $row = mysqli_fetch_row($query);
                        }
        echo "</table>";
    //Close Connection
mysqli_free_result($results);
mysqli_close($conn);
?>  

settings.php包含所有连接信息,并且全部检出。我甚至需要($ _GET ['car_id'])等吗?我可以通过字段名称来呼叫它们吗?

答案会很明显......

2 个答案:

答案 0 :(得分:0)

  

我没有错误,这意味着我连接到数据库和表

这并不意味着。

mysqli_select_db("$conn", "$dbnm")  // That `$conn` should not be inside those quotes.

应该是

mysqli_select_db($conn, $dbnm);  // that $conn has to be a MySQLi link identifier, not an interpolated one.

同时删除所有@并检查这些函数返回的错误。

答案 1 :(得分:0)

请更改以下行。

$conn = @mysqli_connect("$host","$user","$pswd")

$conn = mysqli_connect($host,$user,$pswd)

并且

 @mysqli_select_db("$conn", "$dbnm")

 mysqli_select_db($conn, $dbnm)