我目前有这个:
<?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……
我该怎么做呢?
发布于 2012-03-15 23:43:39
将该硬编码的值转换为变量。
<?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;
?>
发布于 2012-03-15 23:41:47
假设url是这样的: 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
发布于 2012-03-15 23:42:37
使用mysite.com/index.php?id=x
作为URL的基本示例,其中x是Id:
$id = (int)$_GET['id'];
$query = sprintf("
SELECT *
FROM pages
WHERE id = %d",
mysql_real_escape_string($id)
);
当然,在包含连接线的情况下,还应该进行验证。
https://stackoverflow.com/questions/9723077
复制相似问题