首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP / SQL查询url中的动态记录

PHP / SQL查询url中的动态记录
EN

Stack Overflow用户
提问于 2012-03-15 23:38:07
回答 6查看 2.6K关注 0票数 1

我目前有这个:

代码语言:javascript
运行
复制
<?php
  $con = mysql_connect('localhost', 'root', 'dev');
  if(!$con) {
    die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("myDB");
  $query = "SELECT * FROM pages where id=1";
  $result = mysql_query($query);
  $row = mysql_fetch_assoc($result);
  $contents = $row['content'];
  echo $contents;
?>

请参阅此部分:SELECT * FROM pages where id=1

1是记录id,当前是硬编码的。我需要做的是更改它,使其成为url...for示例中的记录id : mysite.com/index.php?2将显示记录id 2……

我该怎么做呢?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-03-15 23:43:39

将该硬编码的值转换为变量。

代码语言:javascript
运行
复制
<?php
    //assumes you have a querystring like: http://mysite.com/index.php?id=3
    $id = $_GET['id'];


  $con = mysql_connect('localhost', 'root', 'dev');
  if(!$con) {
    die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("myDB");


    //Make your variable safe for use with mysql
    $id = mysql_real_escape_string($id);
  $query = "SELECT * FROM pages where id=" . $id;
  $result = mysql_query($query);
  $row = mysql_fetch_assoc($result);
  $contents = $row['content'];
  echo $contents;
?>
票数 3
EN

Stack Overflow用户

发布于 2012-03-15 23:41:47

假设url是这样的: mysite.com/index.php?id=2

在您的index.php中:

代码语言:javascript
运行
复制
<?php
$id = $_GET['id'];
// your sanitizing methods for id to avoid SQL injection

$con = mysql_connect('localhost', 'root', 'dev');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("diy");
$query = "SELECT * FROM pages where id = ".$id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>

当心SQL injection

票数 2
EN

Stack Overflow用户

发布于 2012-03-15 23:42:37

使用mysite.com/index.php?id=x作为URL的基本示例,其中x是Id:

代码语言:javascript
运行
复制
$id = (int)$_GET['id'];

$query = sprintf("
    SELECT * 
    FROM pages 
    WHERE id = %d",
    mysql_real_escape_string($id)
);

当然,在包含连接线的情况下,还应该进行验证。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9723077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档