【问题标题】:Adding values into database with the use of primary and foreign keys使用主键和外键将值添加到数据库中
【发布时间】:2021-01-28 03:54:40
【问题描述】:

我正在尝试使用主键和外键将下拉菜单中选择的值添加到我的数据库中。我试图弄清楚当客户选择下拉框选项时,VALUE 是如何输入到 sql 中的,这与房间表的主要编号相同。我会以某种方式发布下拉框选择 id = rooID 吗?谁能帮我解决这个问题。

下面是我的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>

房间桌:

  • 房间ID(PK)
  • 房间名
  • 说明
  • 房型
  • 床位

预订表:

  • bookingID (PK)
  • 房间名
  • 检查日期
  • 结帐日期
  • 联系电话
  • 预订附加服务
  • 房间 ID (FK)

【问题讨论】:

  • 发布您的 makeabooking.php 文件,因为这是所有操作所在。
  • @jeff Ive 添加到 makeabooking.php 的代码中,可能很多不正确

标签: php html sql foreign-keys primary-key


【解决方案1】:

我已经重写了您的代码 - 希望对您有所帮助

<?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
}
?>

【讨论】:

  • 非常感谢您的帮助,但是当我点击预订时它仍然没有将它添加到我的数据库中它只是出现了两个警告和两个通知
  • 警告说 mysqli_stmt_bind_param() 期望参数 1 是 mysqli_stmt, bool in 是什么意思
猜你喜欢
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 2015-12-21
  • 2021-07-05
相关资源
最近更新 更多