PHP 如果状态来检查可用的地方


PHP if statememt to check available places

我正在尝试检查是否有可用的地方可以预订活动,我正在使用if语句来这样做。如果语句检查预订地点是否少于可用名额总数,如果有可用名额,则应允许预订并插入到clientEvent中,并在活动事件表中更新bookingPlaces。如果没有空位,则应响应已满。它总是回响它已经订满了。我也不确定如何在一个查询中插入和更新。

<?php
session_start();
require("connection.php");
$con=mysqli_connect("$mysql_host","$mysql_user","$mysql_password","$mysql_database");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql ="select bookedPlaces, noOfPlaces from activityEvent";
$result = mysqli_query($con,$sql);
$clientID=$_SESSION['clientID'];
$activityEventID =$_SESSION['activityEventID'];
while($row = $result->fetch_assoc())
{
    $booked =$row['bookedPlaces'];
    $noofPlaces = $row['noOfPlaces'];
}
if($booked < $noofPlaces)
{
    echo "You have booked ";
    $sql="Insert into clientEvent(clientID, activityEventID) Values('$clientID','$activityEventID')";
    $sql= "update activityEvent set AvailablePlaces  = ($available -1) where activityEventID = $activityEventID";
    echo "$sql";
}
else
{
    echo "Fully booked ";
}
if (!mysqli_query($con,$sql))
{
    die('Error: ' . mysqli_error($con));
}
?>

看起来整个if-else块if($booked < $noofPlaces)都在while循环之外。因此,if语句正在评估意外值。

更正后的代码应如下所示。

while ($row = $result->fetch_assoc()) {
    $booked = $row['bookedPlaces'];
    $noofPlaces = $row['noOfPlaces'];
    if ($booked < $noofPlaces) {
        echo "You have booked ";
        $sql = "Insert into clientEvent(clientID, activityEventID) Values('$clientID','$activityEventID')";
        $sql = "update activityEvent set AvailablePlaces  = ($available -1) where activityEventID = $activityEventID";
        echo "$sql";
    }
    else {
        echo "Fully booked ";
    }
}

我给你一个选择:我想bookedPlaces和noOfPlaces的某些行是空的,所以你必须比较它们。您可以像这样创建一个计数器函数:

function counter($row){
$mysqli = new mysqli("localhost", "root", "", "first");
$res = $mysqli->query("SELECT COUNT({$row}) FROM records WHERE {$row} !='' ");  // !=0 or !=[what's your no value]
$row = $res->fetch_row();
return $row[0];
}

现在您可以使用

if(counter('bookedPlaces') < counter('noOfPlacest') {

在此选项中,将fetch_assoc查询保留原样。