SELECT * FROM表ID

时间:2013-07-03 01:22:11

标签: php mysql

我正在尝试从我的数据库中检索信息,具体取决于用户在我的网址中输入的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 个答案:

答案 0 :(得分: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!"; }

答案 1 :(得分:3)

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

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

答案 2 :(得分: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);

答案 3 :(得分:0)

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

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

  2. 使用mysql_escape_string()函数

  3. 应用Mysql转义