简体   繁体   English

根据登录用户的ID显示数据库表中的数据

[英]Displaying data from a database table based on id of user logged in

I'm trying to get certain information from a database according to the user that's logged in. Right now I can get information from the columns and rows but its not user specific. 我正在尝试根据登录的用户从数据库中获取某些信息。现在,我可以从列和行中获取信息,但不是特定于用户的。 Can I use a $_SESSION ? 我可以使用$_SESSION吗? Would that work in the $query ? 可以在$query中工作吗?

PHP: PHP:

$query = "SELECT * ".
"FROM leavetable, users ".
"WHERE leavetable.users_id = users.id ";

$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
    echo ' <tr> ';
    echo ' <td> ';
    echo $row['id'];
    echo ' <td> ';
    echo $row['hours'];
    echo ' <td> ';
    echo $row['email'];
    echo ' <td> ';
    echo $row['username'];
    echo ' <td> ';
}

Yes, but never build your SQL queries like suggested by Mr Shahnewaz's answer. 是的,但是切勿像Shahnewaz先生的回答所建议的那样构建SQL查询。 This kind of approach is vulnerable to SQL injection attacks, I'd suggest you to take some time to read about them and experiment. 这种方法很容易受到SQL注入攻击的影响,建议您花一些时间来阅读有关内容并进行实验。

The proper way to perform a parameterized query is by using a prepared statement: 执行参数化查询的正确方法是使用准备好的语句:

$stmt = $dbh->prepare('SELECT * FROM leavetable WHERE leavetable.users_id = :id');
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->fetch();

The key point to keep in mind is that the query string passed to the prepare method must be a plain hardcoded string. 要记住的关键点是,传递给prepare方法的查询字符串必须是纯硬编码的字符串。 You can use named placeholers (:whatever) where needed, as shown in the example. 如示例所示,可以在需要的地方使用命名的placeholers(:whatever)。

By the way, in this example $dbh would be an instance of the PDO class, which you might consider using instead of the old mysql_* functions. 顺便说一下,在此示例中, $dbh将是PDO类的实例,您可以考虑使用它代替旧的mysql_ *函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM