如何在数组值与数据库值匹配时重定向页面

时间:2017-09-16 07:58:30

标签: php sql database

if (isset($_POST['finalSeats']))
{

从帖子中获取变量

$TicketType =$_POST['Tickettype'];
$seatS=$_POST['finalSeats'];
$EventId=$_POST["Eventid"];

从最后一页获取数组

$cats = array_filter(array_map('trim', explode(',', $seatS)));
$sqlData = array();

使用foreach逐个获取值

foreach($cats as $key => $cat ) {
$stmt = $con->prepare("SELECT * FROM fistevent WHERE `Event_Id`=? AND `TicketType`=? AND `seats`= ?") or die($con->error);
$stmt->bind_param("sss",$EventId , $TicketType,$cat);
$stmt->execute();
$stmt->store_result();

绑定结果

$stmt-> bind_result($id,$Event_Id,$TicketType,$row_name,$seats,$Status);
while($stmt->fetch())
{
$data[] = array($id,$Event_Id,$TicketType,$row_name,$seats,$Status);
$Tickettype=$TicketType;
$Rowname=$row_name;
$Seats=$seats;
$status=$Status;

比较值数组和数据库值

if($Seats===$cat && $status==='Hold')
{
echo'<script>window.location="selection.php";</script>';
}

如果不匹配则更新查询

else
{
$seatS=$_POST['finalSeats'];
$Eventid=$_POST["Eventid"];
$_SESSION['Eventid']=$Eventid;
$cats = array_filter(array_map('trim', explode(',', $seatS)));
$stmt = $con->prepare('UPDATE fistevent SET `Status`="Hold" where `Event_Id`=? AND `seats`= ? ') or die($con->error);
$stmt->bind_param("ss", $_POST['Eventid'], $cat);
foreach($cats as $key => $cat ) {
$stmt->execute();
} 
}

}
}
}

1 个答案:

答案 0 :(得分:1)

根据您更新的代码段,您需要更改代码中的一些内容,例如:

  • 按以下方式更改准备好的陈述,

    if str(i) != "test" and str(i) != "test2":
          print ("i is not test or test2")
        else:
          print ("i is test or test2")
    

    这样,您就不必在代码中使用此$stmt = $con->prepare("SELECT * FROM fistevent WHERE `Event_Id`=? AND `TicketType`=? AND `seats`= ? AND status='Hold'") or die($con->error); 条件语句或if($Seats===$cat && $status==='Hold')语句。

  • 绑定结果后,只需执行以下操作:

    while($stmt->fetch()){ ...

解决方案:

根据下面的对话,要求是:如果数组(E4,E5,E6)已存在于数据库中且状态为hold,则在下一轮中有人选择(E3,E5,E7)(E5在如果数据库和相应的状态被保持,页面应该被重定向,并且(E3,E5,E7)数组中的值不会被更新。仅当数组值为新值且未保持时,才会更新该表。所以这是解决方案代码片段,

...
$stmt->bind_result($id,$Event_Id,$TicketType,$row_name,$seats,$Status);
if($stmt->num_rows){
    header("Location: selection.php");
    exit();
}else{
    $seatS=$_POST['finalSeats'];
    $Eventid=$_POST["Eventid"];
    $_SESSION['Eventid']=$Eventid;
    $cats = array_filter(array_map('trim', explode(',', $seatS)));
    $stmt = $con->prepare('UPDATE fistevent SET `Status`="Hold" where `Event_Id`=? AND `seats`= ? ') or die($con->error);
    foreach($cats as $cat ) {
        $stmt->bind_param("ss", $Eventid, $cat);
        $stmt->execute();
    } 
}