HOWTO · PHP
在 PHP 中使用 MySQL 表插入表單資料
本文展示了 POST 語句如何將表單資料傳送到資料庫中的表。
本頁內容
本教程將介紹如何將資料從 HTML 表單傳送到資料庫中的表。
為此,我們將使用以下步驟:
- 首先,我們將建立一個基本的 HTML 表單來收集資料。
- 然後我們將使用
POST方法將我們的 HTML 表單中的資料傳送到我們資料庫中的一個表中。
我們的資料庫 sample tutorial 中有一個名為 parkinglot1 的表。下面是表格的樣子:
假設我們有一個新條目要新增到表中。我們的新條目如下,BrandName 為 Ferrari,OwnersName 為 Alex,RegistrationNumber 為 KJG564R。
我們如何處理這個問題?首先是建立一個 HTML 表單來收集新資料。
建立一個 HTML 表單來收集資料
我們將在 HTML 表單中擁有三個輸入資料的插槽和一個提交按鈕。我們不需要包含 CarID 插槽,因為 PHP 會自動更新條目。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form- Store Data</title>
</head>
<body>
<center>
<h1>This Form is For Storing Data for OUR Database</h1>
<form action="includes/insert.php" method="POST">
<p>
<label for="CarID">Car ID:</label>
<input type="text" name="CarID" id="CarID">
</p>
<p>
<label for="BrandName">Brand Name:</label>
<input type="text" name="BrandName" id="BrandName">
</p>
<p>
<label for="OwnersName">Owners Name:</label>
<input type="text" name="OwnersName" id="OwnersName">
</p>
<p>
<label for="RegistrationNumber">Registration Number:</label>
<input type="text" name="RegistrationNumber" id="RegistrationNum">
</p>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
輸出:
現在我們可以編寫程式碼將資料傳送到我們的資料庫。
使用 POST 方法將 HTML 表單中的資料傳送到 PHP 資料庫中的表中
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database
$con = mysqli_connect("localhost", $user, $pass, $db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$CarID = $_POST['CarID'];
$BrandName = $_POST['BrandName'];
$OwnersName = $_POST['OwnersName'];
$RegistrationNumber = $_POST['RegistrationNumber'];
$sql = "INSERT INTO parkinglot1 (CarID,BrandName,OwnersName, RegistrationNumber)
VALUES ('$CarID','$BrandName','$OwnersName', '$RegistrationNumber')";
mysqli_query($con, $sql);
header("Location: ../form.php"); // Return to where our form is stored
?>
header() 函式將返回我們的 HTML 表單,我們可以在其中填寫我們想要插入的值,如下所示:
提交資料後,更新後的表格應如下所示: