SELECT * FROM Table Where ID


SELECT * FROM Table Where ID

我正试图根据用户在URL中键入的ID从数据库中检索信息。

例如:如果用户A转到www.examplerl.com/index.php?id=1,它将回显id为1的用户信息。如果id是2、3等,也是一样的。用户通过另一个名为submit.php的文件中的表单输入信息。

这是我根据ID:检索数据的代码

<?php
    $id = $_GET['id'];
        //Variables for connecting to your database.
        $hostname = "";
        $username = "";
        $dbname = "";
        $password = "";
        $usertable = "";
        //Connecting to your database
        $con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to 
        connect to database! Please try again later.");
        mysql_select_db($dbname, $con);
        $query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
        $result = mysql_query($query, $con);
    echo "Hello, " . $result['name'];
 ?> 

关于我的SELECT请求是否错误,有什么想法吗?

编辑

这是我在一个表中显示数据的代码。这很好用。

 <?php
        //Variables for connecting to your database.
        $hostname = "";
        $username = "";
        $dbname = "";
        $password = "!";
        $usertable = "";
        //Connecting to your database
        $con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to 
        connect to database! Please try again later.");
        mysql_select_db($dbname, $con);
        //Fetching from your database table.
        $query = "SELECT * FROM $usertable";
        $result = mysql_query($query, $con);
        echo "<table border=1>
        <tr>
        <th> ID </th>
        <th> Name </th>
        <th> Age </th>
        </tr>";
        while($record = mysql_fetch_array($result)) {
            echo "<tr>";
            echo "<td>" . $record['id'] . "</td>";
            echo "<td>" . $record['name'] . "</td>";
            echo "<td>" . $record['age'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
 ?>

→试试这个:

您应该考虑使用PHP PDO,因为它更安全,而且是一种更面向对象的方法:

$usertable = "";
$database  = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
     $R = $statement->fetchAll( PDO::FETCH_ASSOC );
     for( $x = 0; $x < count($R); $x++ ) {
        echo "<tr>";
        echo "<td>" . $R[ $x ]['id'] . "</td>";
        echo "<td>" . $R[ $x ]['name'] . "</td>";
        echo "<td>" . $R[ $x ]['age'] . "</td>";
        echo "</tr>";
     }
}
else { echo "Error!"; }

您需要使用mysql_fetch_assoc函数来检索结果。

 $result = mysql_fetch_assoc(mysql_query($query, $con));    
 echo "Hello, " . $result['name'];

您应该在检查mysql_querys:时出错

$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
    echo mysql_error();

您还应该检索结果:

$array = mysql_fetch_assoc($result);

我会考虑一些安全功能,比如

  1. 检查是否设置了$_GET['id'],是否为int

  2. mysql_escape_string()函数实现Mysql转义