PHP选择单个结果

时间:2014-04-27 10:41:05

标签: php search

我创建了一个PHP表单,允许用户注册并登录。现在我创建了另一个名为 View.php 的页面,它将显示我的MySQL数据库中的所有注册用户。我使用的代码是

while($row=mysqli_fetch_assoc($sql))...

它成功显示了所有用户

现在我创建了另一个名为 profile.php 的PHP页面。我想在 view.php 的每个结果中添加一个链接,它将重定向到 profile.php?user =(他们的用户名)。但我不知道如何。

3 个答案:

答案 0 :(得分:0)

view.php 中,考虑到您有一个名为&#39; username&#39; ,更改以下内容: 请不要,最好放置ID列如果您想要输入ID列,只需将$row['username']更改为$row['id'],并在profile.php <中的查询中进行相同操作/ p>

<?php
...
            while($row=mysqli_fetch_assoc($result)) {
                    echo "---------------------<br/>";
                    echo "<b>".$row['fullname']."</b><br/>";
                    echo "<small><i>".$row['course']."</i></small><br/>";
                    echo "<small><a href = 'friends.php?user=".$row['username']."'>[View Profile]</a></small><br/>";
                    echo "---------------------<br/><br/>";

            }

    ?>

在你的 的 profile.php

<?php session_start();

        if($_SESSION['logged_in']==false) {
                header("Location:login.php");
        }


        include("header.php");

?>

<html>
<head>
        <title>View School-Mates</title>
</head>
        <body>
                <center>
                        <h1>My School-Mates</h1>
                        <small>View or Add them in your Trust List</small>
                        <br/><br/>
                        <hr>
                </center>

<?php
 try {
        $dbh = new PDO('mysql:host=localhost;dbname=test_basic', "root", "");

        $stmt = $dbh->prepare("SELECT * FROM USERS WHERE username= ?");
        if ($stmt->execute(array($_GET['user']))) {
            while ($row = $stmt->fetch()) {
                //here you will have your row with all your username data
            }
        }

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

?>

</body>
</html>

请详细了解PDO from herehow to do connections这是必需的,因为您从$ _GET变量中获取数据,因此您需要avoid for sql injection

希望这是你想要的,如果没有,请告诉我,以便我可以调整代码

答案 1 :(得分:0)

我不知道你用来实现结果的代码,但有类似的东西:

$query = "SELECT * FROM database WHERE id=$id";
$query = mysql_query($query);

这将根据用户ID

过滤出个人资料页面

答案 2 :(得分:0)

在这一行:

echo "<small><a href = 'profile.php?user=$them'>[View Profile]</a></small><br/>";

而不是使用固定的$ them,只需使用$ row ['id']。然后,您可以在profile.php文件中获取具有该ID的用户:

$id = $_GET['user'];
$sql = "SELECT * FROM users where id = $id";

请注意,此代码很容易被sql注入。我只发布它以使这个想法更容易理解。请参阅here如何正确完成。