1

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

例如:如果用户 A 访问 www.exampleurl.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>";
 ?>
4

4 回答 4

4

→ 试试这个:

您应该考虑使用 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!"; }
于 2013-07-03T01:28:52.190 回答
3

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

 $result = mysql_fetch_assoc(mysql_query($query, $con));    
 echo "Hello, " . $result['name'];
于 2013-07-03T01:25:31.570 回答
2

您应该在检查 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);
于 2013-07-03T01:26:02.117 回答
0

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

  1. 检查是否$_GET['id']已设置以及是否已设置int

  2. mysql_escape_string()使用函数应用 Mysql 转义

于 2013-07-03T02:53:57.810 回答