2013-12-19 106 views
1

所以我想检查一个帖子是否存在于数据库中,但是我有一些重定向的问题。 这是迄今为止我的工作:检查帖子是否存在

echo '<br>';//the $row part tells the DB what post his looking on 
echo '<a href="comments.php?post_id='. $row['id'].'">View comments</a>'; 

这是显示评论按钮,导致在那里你看到的帖子评论的部分。


<?php 
require_once ('checkp.php'); 

我有要求后检查脚本一次。


<?php 
include ('variables.php'); 
//connects to DB 
$dbc=mysql_connect($host,$user,$pass); 


if ($dbc) { 


} else { 

echo ('Failed to connect to MySql; '. mysql_error()); 

} 


//selects db from MySQl 
$sqldb=mysql_select_db('a2318052_blog'); 

$pid=$_GET['post_id']; 

$query1="SELECT * FROM posts_b WHERE id='$pid'"; 
$sql=mysql_query($query); 

if ($sql) { 


} else { 

echo "cant run query"; 

} 


if (mysql_num_rows($sql) > 0) { 

echo "that post does not exist!"; 

} else { 

header ("location: comments.php?post_id='. $pid.'"); 

} 

?> 

这是检查一个空的结果的脚本,然后重定向回。我相信,它与这里的重定向的东西:;

+1

你有一个严重的SQL注入孔的pid

$pid = intval($_GET['post_id']); // for security 

。 –

+0

为什么你回应说,如果你的查询得到了结果,那么帖子不存在? – putvande

+0

这是一个很好的问题 –

回答

0

你可能不希望围绕POST_ID单引号...

(头() “位置的comments.php POST_ID =? '$ PID。'”)
header ("location: comments.php?post_id=$pid"); 
1

您对混合重定向引号:

"location: comments.php?post_id='. $pid.'" 

应该

"location: comments.php?post_id=". $pid 

在PHP中的点是使用d来连接字符串。卜有你与“开弦和与”关闭它

编辑:。另外,作为别人已经注意到你正在使用的查询,而不是QUERY1的 此外,我想,而不是:

if (mysql_num_rows($sql) > 0) { 

echo "that post does not exist!"; 

你想别的东西:

if (mysql_num_rows($sql) == 0) { 

echo "that post does not exist!"; 
+1

或''location:comments.php?post_id = $ pid“'? – putvande

+0

好吧,他使用的是分数,所以我猜他误解了连接是如何工作的。 – nowhere

+0

或者他可能会感到困惑。 –

0
$query1="SELECT * FROM posts_b WHERE id='$pid'"; 
$sql=mysql_query($query); 

您使用$查询,而不是$ QUERY1这可能是问题(与串联的东西沿着其他用户具有点。删除)。

还有一些其他的东西,比如我想你混淆了你的if/else语句在这里:

if (mysql_num_rows($sql) > 0) { 

echo "that post does not exist!"; 

} else { 

header ("location: comments.php?post_id='. $pid.'"); 

} 

也许你想要的顺序被逆转?


此外,你应该看看避免SQL注入! 发送带有$ GET变量的查询非常危险,因为用户可以操纵URL并发送恶意查询。

$pid=$_GET['post_id']; 

Prepared statements are ideal,但现在,你可以使用你的周围$ GET变量mysql_real_escape_string。它阻止人们发送你真正不想做的查询。

+0

它现在可以工作,但是当我使用require_once时,它使我处于重定向循环中...你知道如何解决它吗? –

+0

我在想你想把重定向改成别的东西。 'header(“location:comments.php?post_id ='。$ pid。'”);' 该行几乎只是一直保持着自己。你得到comments.php?post_id = x,然后它会再次发送给你,并且如果评论是有效的(并且你已经做出了上面的更改),再次,再次循环。 – stephen

0

第一个变化之后

if (mysql_num_rows($sql) == 0) 
{ 
    echo "that post does not exist!"; 
} 
else 
{ 
    header("Location: comments.php?post_id=".$pid); 
} 
相关问题