使用URL中的ID从mySQL选择数据 [英] Selecting data from mySQL using the ID in URL

查看:83
本文介绍了使用URL中的ID从mySQL选择数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含列的表

GroupID | GroupName | GroupDesc | Overs |
-----------------------------------------
1       | Test Group|Description| Yes   |

我有一个名为list.php的页面,它当前在groups表中(上方)为数据库中的每一行创建URL.

I have a page called list.php and it currently creates the URL for each row in the DB in the groups table(above).

代码不是最漂亮的,但我认为这是他的代码

The code is not the prettiest but I think it works this is he code

list.php

<?php 
    $result = mysql_query("SELECT * FROM groups");

    while($row = mysql_fetch_array($result))
        {
            echo "<div class=\"divider\">";
            echo "<a href=\"group.php?id=";
            echo $row['GroupID'];
            echo "\">";
            echo $row['GroupName'];

            echo "</a>";
            echo "<br><br>";
            echo $row['GroupDesc'];
            echo "<br>";
            echo "Over 18's: ";
            echo $row['AgeRes'];
            echo "</div>";
        }
?>

然后创建一个URL,例如 http://domainname.com/group/group.php?id = 1

This then creates a URL such as this http://domainname.com/group/group.php?id=1

这是我的问题所在-如何使用URL中的ID部分从上面的数据库中选择相关行?

This is where my questions are - how would I select the relevant row from the DB above using the ID section in the URL?

我的第二个问题是我们如何停止这种可注入SQL的行为?

My second question would be how would we stop this being SQL injectable?

我对所有这些都是新手,所以我很乐意就此以及任何好的阅读资料提供答案,以便我进一步发展自己的技能.

I am kind of new to all this so I would love an answer on this and any good reading sources so I can develop my skills further.

谢谢

推荐答案

问题1:您需要检索请求变量并将其包含在SQL查询中:

Q1: You need to retrieve the request variable and include in your SQL query:

$result = mysql_query("SELECT * FROM groups WHERE id = '" . $_GET['id'] . "'");

Q2:在包含在查询中之前,您应该先对值进行转义:

Q2: You should escape the value first before including in your query:

$id = (int)mysql_real_escape_string($_GET['id']);

然后将查询更改为以下内容:

Then change your query to the following:

$result = mysql_query("SELECT * FROM groups WHERE id = '" . $id . "'");

这篇关于使用URL中的ID从mySQL选择数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆