简体   繁体   English

如何处理PHP中sql查询的单个结果?

[英]How do I process a single result from an sql query in PHP?

I am using the stored $_SESSION username (stored in the $username variable) to obtain the user's id using the following query in PHP: 我正在使用存储的$ _SESSION用户名(存储在$ username变量中)来通过PHP中的以下查询获取用户的ID:

$query = mysql_query("SELECT id FROM users WHERE username = '".$username."'");

I then process the query result as follows: 然后,我按以下方式处理查询结果:

$userid = mysql_fetch_row($query);

Because I am logged in as a demo user, the user id that this query should return is: 12. However, when I echo $userid['id'] I get this output: 因为我是作为演示用户登录的,所以该查询应返回的用户ID为:12.但是,当我回显$ userid ['id']时,我得到以下输出:

1111

Is this not a proper way of processing the data from the query? 这不是处理查询数据的正确方法吗? Should I be using mysql_fetch_row() if I am only expecting a single result? 如果我只期望一个结果,是否应该使用mysql_fetch_row()?

I have also tried running the query in PHPMyAdmin and it returns the expected result just fine. 我也尝试在PHPMyAdmin中运行查询,它返回预期的结果就好了。

fetch the results using: 使用以下命令获取结果:

    $query="SELECT id FROM users WHERE username ='$username'";
    $res=mysql_query($query);
    while($row=mysql_fetch_row($res))
    {
                $id=$row[0]; //change to the column number you are using to store id
    }

try this 尝试这个

   while($userid = mysql_fetch_array($query))
    {
      echo $userid['id'].'<br />';
    }

Your query is vulnerable to SQL injection attacks and you are using deprecated libraries which will be removed from future versions of PHP. 您的查询容易受到SQL注入攻击的影响,并且您正在使用不赞成使用的库,这些库将从将来的PHP版本中删除。

I recommend moving to mysqli ( documentation ), which will help to protect you from injection attacks with its prepared statements ( documentation ). 我建议转到mysqli( 文档 ),这将通过其准备好的语句( 文档 )帮助保护您免受注入攻击。

Your query appears correct. 您的查询显示正确。 If you run SELECT id FROM users WHERE username = 'demo' in PHPMyAdmin or SQL command line, what do you get? 如果您在PHPMyAdmin或SQL命令行中运行SELECT id FROM users WHERE username = 'demo' ,您会得到什么? Is username a UNIQUE field or do you have two accounts called demo ? usernameUNIQUE字段,还是您有两个名为demo帐户?

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

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