gpt4 book ai didi

php - 对于公共(public)配置文件系统,查询 WHERE id ='. $something .' 时出现 Sql 错误

转载 作者:行者123 更新时间:2023-11-30 00:12:42 24 4
gpt4 key购买 nike

我正在制作一个公共(public)文件系统,例如facebook,youtube......当用户注册时,它会使用他的信息创建自己的个人资料,并为其提供一个类似于 "www.mysite.com/userprofile.php?id=1" 的 URL,任何人无需登录即可看到该 URL,任何访问该 url 的人都可以看到该配置文件,userprofile.php 从数据库获取数据。这是我的代码:

<?php 
$id = $_GET["id"];
$query = ("SELECT username,email FROM table WHERE id=" . $id . " LIMIT 1");
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['username']. " - ". $row['email']; }
?>

它在访问“www.mysite.com/userprofile.php?id=1”时工作,它获取id为1的用户信息,然后回显它们,但是当我访问“www.mysite.com/userprofile.php”它给出了这个sq错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 1' at line 1

即使我删除“LIMIT 1”,它也会出现此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

还有一件事,如果有人修复了错误,你能告诉我如何将 "www.mysite.com/userprofile.php?id=1" 转换为 "www .mysite.com/user1" 以及当用户配置文件不存在时如何返回 404 错误

有什么方法可以防止 SQL 注入(inject)吗?

谢谢你的提前:)

最佳答案

当您导航到 /userprofile.php 而不是 /userprofile.php?id=123 时,您实际上是在运行以下查询:

SELECT username,email FROM table WHERE id= LIMIT 1

这是一个无效的 SQL 语句。有很多方法可以修复它,但最简单的可能是这样的:

<?php 
$id = $_GET["id"];
if(!empty($id)) {
// typecast it for at least a little security
$query = ("SELECT username,email FROM table WHERE id=" . (int) $id . " LIMIT 1");
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['username']. " - ". $row['email']; }
} else {
echo "Please provide a user ID."
}

这会检查用户 ID 是否已设置且不为空,并在运行查询之前将其类型转换为 int。

话虽如此,您确实应该研究一下 mysqliPDO对于这种事情。

关于php - 对于公共(public)配置文件系统,查询 WHERE id ='. $something .' 时出现 Sql 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23921239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com