PHP $ _POST [key]返回值

时间:2015-03-25 18:46:14

标签: php post get

我遇到了一个PHP问题文件,它提供了与产品购物车功能相关的代码示例。当我浏览代码示例时,如果检查的条件(如果分配了$ _POST [key]值的变量)为false,则会遇到某些PHP。以下是与我面临的问题相关的代码示例。

nicepage.php

$id=$_GET['previd'];
$SQL = "select * from pro where prId=".$id;
$runSQL = mysql_query($SQL) or die(mysql_error());
$details = mysql_fetch_array($runSQL);
echo "<p>Catalogue Item Number: ".$details['prId'];
echo "<p>". strtoupper($details['prName']);
echo "<p>".$details['prDescrip'];
echo "<p><img src=images/".$details['prPicName'].">";
echo "<p>£".$details['prPrice'];
echo "<p>".$details['prQuantity']." items for you to get!" ;
echo "<form method=post action=greatpage.php>" ;
echo "<p>Enter how many: ";
echo "<input type=text name=newqu size=5 maxlength=3>";
echo "<input type=submit value='Get them'>";
echo "<input type=hidden name=newid value=".$id.">";
echo "</form>" ;
echo "</center>";
echo "</body>";
echo "</html>";

greatpage.php

$theid=$_POST['newid'];
$thequ=$_POST['newqu'];
if (!$theid)
{
echo "<p>Nothing new is added, show the stuff from before";
}
else
{
if (!$thequ or $thequ==0)
{
echo "<p>Error!";
echo "<p><a href=nicepage.php>Enter correct value!</a>";
exit;
}
else
{
$theSQL="select prQuantity from pro where prId=".$theid;
$runtheSQL=mysql_query($theSQL) or die (mysql_error());
$info=mySQL_fetch_array($runtheSQL);
$ourqu=$info['prQuantity'];
if ($thequ > $ourqu)
{
echo "<p>Not good!";
echo "<p><a href=nicepage.php> Do it again!</a>";
exit;
}
else
{
echo "<p>Great, item added!";
$_SESSION['storage'][$theid]=$thequ;
}
}
}

上面的代码示例提供了与该问题相关的部分PHP脚本。

我是一个相对较新的PHP程序员,因此我会因为任何错误而原谅我。

我想了解为什么检查$theid$thequ是否等于false而不是使用像isset($_POST['key'])这样的函数检查是否$_POST全局变量在分配给两个PHP $theid$thequ变量之前设置。

在上面的代码示例中,哪些情况可能导致!$theid!$thequ成立?

我非常感谢任何可以解决这个难题的人。

2 个答案:

答案 0 :(得分:1)

所以让我们打破这个

if(!$theid)

这是检查变量是否存在的不良方法。你应该做更像if(isset($_POST['newid']))的事情,这将明确地告诉你字段已经提交

if (!$thequ or $thequ==0)

同样,我们检查是否存在该值是否很差,但第二个是查看该字段是否已提交为空的粗略方式。如果您提交一个空字段,则其值为''或空字符串。由于空字符串为false y,因此您可以查看anything PHP considers to be false。所以'' == 0是真的。我至少会使用''empty()而不是0(这样可以提高可读性)。

接下来,您的SQL对SQL injection开放。

最后,请不要将mysql_函数用作they are deprecated and will soon be removed from PHP

答案 1 :(得分:0)

如果使用isset(),它会检查变量是否存在。所以,如果你说

$id="";

结果将为TRUE,因为变量存在。但是空的。

最好的方法是;

if(empty($id)) {

//your code
} else {

//your code when NOT empty
}