简体   繁体   English

使用会话信息的PHP查询数据库

[英]PHP Query Database Using Session Information

I have been programming for a while but pretty new to PHP. 我已经进行了一段时间编程,但是对PHP来说还很陌生。 I am have run into a problem. 我遇到了问题。 My site has a login/register screen and once logged into the account, I am trying to echo information from the users database entry. 我的网站有一个登录/注册屏幕,一旦登录到该帐户,我试图从用户数据库条目中回显信息。 For example if I want to display the content "Balance" I have been trying the following code: 例如,如果我想显示内容“余额”,则尝试使用以下代码:

<?php 
    $data = mysql_query("SELECT * FROM users WHERE username=username") or die(mysql_error()); 
    while($info = mysql_fetch_array( $data )) 
    { 
        Print $info['balance']; 
    } 
?>

The idea is that the script will query the database using the username stored in the session then goto the named field. 这个想法是脚本将使用会话中存储的用户名查询数据库,然后转到命名字段。

When there is only one registered user, it appears to work, however; 但是,只有一个注册用户时,它似乎可以工作; once multiple users enroll, it echoes the value from ALL users (ex. $7.50$10.12). 一旦多个用户注册,它将回显所有用户的值(例如$ 7.50 $ 10.12)。

Thanks for your help in resolving this issue! 感谢您为解决此问题所提供的帮助!

Currently you are not comparing the username to a variable, but you are comparing it to itself, which means it will always be true. 当前,您并未将用户名与变量进行比较,而是将其与自身进行了比较,这意味着它将始终为真。

<? 

$username = $_SESSION['username'];//or other methods like $_POST['username'] or $_GET['username'], depending on how you intend to get the username;

$data = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error()); 

while($info = mysql_fetch_array( $data )) 
{ Print $info['balance']; }

 ?>

You neet to make sure the $username is escaped (if comes from user input) as well as start using mysqli or pdo instead of mysql. 您需要确定$ username是否已转义(如果来自用户输入),以及开始使用mysqli或pdo而不是mysql。

And, of course, I'm assuming you are using session_start() somewhere and actually assigning the username to the session. 而且,当然,我假设您在某处使用session_start()并将实际的用户名分配给该会话。

Hope this helps! 希望这可以帮助!

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

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