来自url的PHP / SQL查询动态记录

时间:2012-03-15 15:38:07

标签: php

我目前有这个:

<?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获取记录ID ...例如:mysite.com/index.php?2将显示记录ID 2 ...

我该怎么做?

6 个答案:

答案 0 :(得分:3)

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

<?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;
?>

答案 1 :(得分:2)

让我们说网址是这样的:mysite.com/index.php?id = 2

你的index.php中的

<?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 :(得分:1)

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

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

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

当然包含您的连接线,您也应该验证。

答案 3 :(得分:1)

使用GET方法解释URL数据。首先,您应该look here for how to use ithere for how to read it

基本上,您的网址将如下所示:

mysite.com/index.php?id=2

然后,你可以像这样读取URL变量:

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

mysql_real_escape_string()将有助于避免SQL注入,但需要现有连接,因此您的代码将如下所示:

<?php
  // Set up connection

  $id = mysql_real_escape_string($_GET['id']);
  $query = 'SELECT * FROM pages where id = '.$id;

  // Run the query
?>

答案 4 :(得分:0)

您可以使用正则表达式从URL中提取它。

$retval=preg_match( "@(\d+)$@", $_SERVER['REQUEST_URI'], $match );
$index=-1;
if( $retval ) { 
    $index = $match[1];
}

此方法允许您继续使用问题中描述的URL方案,而无需预先添加id =。这是否是个好主意可能是有争议的。

答案 5 :(得分:-1)

http://pastebin.com/NEZe7jjL

<?php

$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'user', 'password', array(
    PDO::ATTR_EMULATE_PREPARES => true,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8',
));

$stmt = $dbh->prepare('SELECT * FROM `pages` WHERE `id` = :page');
$stmt->bindValue(':page', $_GET['page'], PDO::PARAM_INT);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);

?>

yoursite.com/index.php?page=2