简体   繁体   中英

php mysql trying to use empty to only add a new record in table if a primary key exists in a different table

I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id. Any help would be great.

if($_SERVER["REQUEST_METHOD"]== "POST") {
        $party_id = (int)$_POST["partyid"];
        $name = $_POST["name"];
        $date = $_POST["date"];
        $length = (int)$_POST["length"];
        $sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";  
        $res = mysqli_query($link, $sql); 
        if(empty($party_id)) { #Were any records found?
            print '<p>No Parties with that ID found! please press the back button to select another party</p>'; 
        } else {
            $record = mysqli_fetch_assoc($res);
            $party_name =  $record["party_name"];
            $price = $record["price"];
            $cost = $price * $length;
            $bookable = true;
            $sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database"); 

A simpler way might be to just check if the query returned any results like this.

if($_SERVER["REQUEST_METHOD"]== "POST") {
        $party_id = (int)$_POST["partyid"];
        $name = $_POST["name"];
        $date = $_POST["date"];
        $length = (int)$_POST["length"];
        $sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";  
        $res = mysqli_query($link, $sql); 

        if ( mysqli_num_rows($res ) == 0 ) {
            print '<p>No Parties with that ID found! please press the back button to select another party</p>'; 
        } else {
            $record = mysqli_fetch_assoc($res);
            $party_name =  $record["party_name"];
            $price = $record["price"];
            $cost = $price * $length;
            $bookable = true;
            $sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM