简体   繁体   English

使用主键和外键将值添加到数据库中

[英]Adding values into database with the use of primary and foreign keys

Im trying to add the chosen values from my drop down menu into my database by using primary and foreign keys.我试图通过使用主键和外键将下拉菜单中选择的值添加到我的数据库中。 Im trying to figure out how when the customer selects the drop down box option, the VALUE is entered into sql, which is the same number as room table primary.我试图弄清楚当客户选择下拉框选项时,VALUE 是如何输入到 sql 中的,这与房间表的主编号相同。 Would i somehow post the drop down box select id = rooID?我会以某种方式发布下拉框 select id = rooID 吗? Can anyone please help me with this.谁能帮我解决这个问题。

Below is my makeabookingphp code:以下是我的 makeabookingphp 代码:

<!DOCTYPE HTML>
<html><head><title>Make a Booking</title> </head>
 <body>

<?php
 //function to clean input but not validate type and content
 function cleanInput($data) {  
 return htmlspecialchars(stripslashes(trim($data)));
 }

 //the data was sent using a formtherefore we use the $_POST instead of $_GET
 //check if we are saving data first by checking if the submit button exists in the array
if (isset($_POST['submit']) and !empty($_POST['submit']) and ($_POST['submit'] == 'Book')) {
 //if ($_SERVER["REQUEST_METHOD"] == "POST") { //alternative simpler POST test    
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);


 //prepare a query and send it to the server
 $query = 'SELECT room.roomID, room.roomname, room.roomtype, booking.bookingID, booking.roomID, booking.roomname
FROM room
INNER JOIN booking
ON room.roomID = booking.roomID';



 if (mysqli_connect_errno()) {
    echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
    exit; //stop processing the page further
 };

 //validate incoming data - only the first field is done for you in this example - rest is up to you do

  $error = 0; //clear our error flag
  $msg = 'Error: ';
  if (isset($_POST['roomname']) and !empty($_POST['roomname']) and is_string($_POST['roomname'])) {
   $fn = cleanInput($_POST['roomname']); 
   $roomname = (strlen($fn)>50)?substr($fn,1,50):$fn; 
   //check length and clip if too big
   //we would also do context checking here for contents, etc       
   } else {
   $error++; //bump the error flag
   $msg .= 'Invalid'; //append eror message
   $roomname = '';  
   } 

   $roomname = cleanInput($_POST['roomname']);        

   $checkindate = cleanInput($_POST['checkindate']);        

   $checkoutdate = cleanInput($_POST['checkoutdate']);   

   $contactnumber = cleanInput($_POST['contactnumber']); 

   $bookingextras = cleanInput($_POST['bookingextras']);       
   
   //save the customer data if the error flag is still clear
   if ($error == 0) {
    $query1 = "INSERT INTO booking (roomname, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
    $stmt = mysqli_prepare($DBC,$query1); //prepare the query
    mysqli_stmt_bind_param($stmt,'sssss', $roomname, $checkindate, $checkoutdate,$contactnumber,$bookingextras); 
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);    
    echo "<h2>Booking saved</h2>";        
} else { 
  echo "<h2>$msg</h2>".PHP_EOL;
}      
mysqli_close($DBC); //close the connection once done
}
?>
<h1>Make A Booking</h1>
<h2><a href='menu.php'>[Return to the main page]</a></h2>

<form method = "post" action = "processbooking.php">
<p>
<label for = "rooID">Room: (name, type, beds): </label>
<select id = "rooID" name = "rooID" required>
<option name = "" value = "" disabled selected>Select</option>
<option name = "1" value = "1">Kellie, S, 5</option>
<option name = "2" value = "2">Herman, D, 2</option>
<option name = "3" value = "3">Scarlett, D, 2</option>
<option name = "4" value = "4">Jelani, S, 5</option>
<option name = "5" value = "5">Sonya, S, 4</option>
<option name = "6" value = "6">Miranda, S, 2</option>
<option name = "7" value = "7">Helen, S, 2</option>
<option name = "8" value = "8">Octavia, D, 3</option>
<option name = "9" value = "9">Bernard, D, 5</option>
<option name = "10" value = "10">Dacey, D, 1</option>
</select>
</p> 

<p>
<label for="checkindate">Check in date: </label>
<input type="date" name="checkindate"required> 
</p>  
<p>
<label for="checkout">Check out date: </label>
<input type="date" name="checkoutdate"required> 
</p>  
<p>  
<label for="contactnumber">Contact number: </label>
<input type="tel" name="contactnumber" required> 
</p>
<p>
<label for="bookingextras">Booking extras: </label>
<input type="text" name="bookingextras" size="100" minlength="5" maxlength="200"  required> 
  </p> 

<input type="submit" name="submit" value="Book">
<a href="menu.php">[Cancel]</a>

</form>
</body>
</html>

Room table:房间桌:

  • roomID (PK)房间号(PK)
  • roomname房间名
  • description描述
  • roomtype房型
  • beds

Booking table:预订表:

  • bookingID (PK)预订ID(PK)
  • roomname房间名
  • checkindate登记日期
  • checkoutdate离开日期
  • contactnumber联系电话
  • bookingextras预订附加服务
  • roomID (FK)房间号 (FK)

I've rewritten your code - hope it helps我已经重写了您的代码-希望对您有所帮助

<?php
 //function to clean input but not validate type and content
 function cleanInput($data) {  
 return htmlspecialchars(stripslashes(trim($data)));
 }

// STEP 1 -test if form has been submitted
if (isset($_POST['submit']) && ($_POST['submit'] == 'Book')) {
    // STEP 2. process the inputs
    // get inputs - clean or set a default if not supplied
   $roomID        = isset( $_POST['rooID'] )         ? cleanInput($_POST['rooID'])         : -1;                
   $checkindate   = isset( $_POST['checkindate'] )   ? cleanInput($_POST['checkindate'])   : "";        
   $checkoutdate  = isset( $_POST['checkoutdate'] )  ? cleanInput($_POST['checkoutdate'])  : "";   
   $contactnumber = isset( $_POST['contactnumber'] ) ? cleanInput($_POST['contactnumber']) : ""; 
   $bookingextras = isset( $_POST['bookingextras'] ) ? cleanInput($_POST['bookingextras']) : "";
    
    // STEP 3 validate/clean the inputs (don't trust anything coming in)
    // validate all the inputs according to business rules
    $error = 0;
    $errMsg  = [];
    if( roomID == -1 ) {
        $error++;
        $errMsg[] = "Room not selected";
    }
    // do all other inputs
    
    // proceed if no errors
    if( $error != 0 ) {
        // STEP 4 connect to the database
        // connect to the database
        include "config.php"; //load in any variables
        $DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
        if (mysqli_connect_errno()) {
            echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
            exit; //stop processing the page further
        };      
        // STEP 5 check if the roomID is valid
        // if roomID is valid then continue
        $query = "SELECT roomID FROM roomTable WHERE roomID=".$roomID;
        $result = $DBC->query( $query ); // ???? check the syntax of this line
        if( $result ) { // something returned ???? check syntax
            // STEP 5 update the relevant table(s)
            $query1 = "INSERT INTO booking (roomID, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
            $stmt = mysqli_prepare($DBC,$query1); //prepare the query
            mysqli_stmt_bind_param($stmt,'issss', $roomID, $checkindate, $checkoutdate,$contactnumber,$bookingextras); 
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);   
            echo "<h2>Booking saved</h2>";
        }
    } else {
        // STEP 3.1 show user messages of what went wrong
        echo $errMsg;
    }
    mysqli_close($DBC); //close the connection once done
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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