PHP + MySQL + Cookies,为什么这个加载不正确?

时间:2013-03-08 23:18:16

标签: php mysql cookies postback

我在代码的各个部分都有一个包含2个MySQL语句的PHP页面。我正在使用生成的结果集来设置cookie值,然后再调用它。然而,当我调用cookie数据时,它不会在第二次刷新之后更新cookie值的显示。为了更好地理解,以下是代码的3个部分:

<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";

    $result = ExecuteSql($SqlStatement);
    if(mysqli_num_rows($result) == 1)
    {
        $row = mysqli_fetch_array($result);
        setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
        setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
        setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
    }
}
?>

这是从回发中提取数据的代码。我认为这是不正确的部分,但我不确定。

<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>

这是将cookie数据加载到字段中的代码,以及使第二次刷新正确显示的部分。

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
  <select name="cboDeceased" id="cboDeceased">
    <option>Select...</option>
    <?php
    $SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";

    $res = ExecuteSQL($SqlStatement);

    while($row = mysqli_fetch_array($res))
    {
        echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
    }
?>

这是将基于ID的变量传递给第一个代码块的代码。这部分工作正常。

function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}

这是ExecuteSQL函数的代码。我知道这不是问题。

我认为问题出现在第一个代码块中,但我不确定。我已尽力而为,现在已经没想到了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

除了DaveRandom上面提到的SQL注入之外,看一下关于setcookie如何工作的php手册:

http://php.net/manual/en/function.setcookie.php

具体提到信息被注入到标题中,因此在下一页加载之前不可用。你可能想做类似

的事情
if(isset($_COOKIE['deceasedID']))
{
    $deceasedID = $_COOKIE['deceasedID'];
}
else
{
    setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
    $deceasedId = $row['PK_Deceased'];
}