我现在有这个:
<?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。。。
我该怎么做?
将硬编码的值转换为一个变量。
<?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;
?>
假设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注入
使用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)
);
当然,在包含连接线的情况下,您还应该进行验证。
URL数据使用GET方法进行解释。首先,你应该看看这里如何使用它,以及这里如何阅读它
基本上,你的URL会像这样:
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
?>
您可以使用正则表达式从URL中提取它。
$retval=preg_match( "@('d+)$@", $_SERVER['REQUEST_URI'], $match );
$index=-1;
if( $retval ) {
$index = $match[1];
}
这种方法允许您继续使用您在问题中描述的URL方案,而无需预写id=。这是不是一个好主意可能还有待商榷。
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);
?>
你的网站.com/index.php?page=2