[英]How can I insert data into two or more tables at once in PHP and MySQL?
我正在嘗試使用php將html表單中的數據插入mysql數據庫。 僅插入一個表(客戶表),而不插入包表。Am尋求幫助,我如何一次將其插入兩個表中。 這是代碼...請幫助
<?php
include "includes/connection.php";
//Customer Table
$firstName = $_POST['inputFirstName'];
$lastName = $_POST['inputLastName'];
$gender = $_POST['inputGender'];
$address = $_POST['inputAddress'];
$mobileNumber = $_POST['inputMobilePhone'];
$workAddress = $_POST['inputAddress'];
$age = $_POST['inputAge'];
//Package Information
$PackageName = $_POST['inputPackageName'];
$PackageWeight = $_POST['inputPackageWeight'];
$PackagePrice = $_POST['inputPackagePrice'];
$DepartureDestination = $_POST['inputDepartureDestination'];
$finalDestination = $_POST['inputFinalDestination'];
//$DeliveryOption = $_POST['inputDeliveryOption'];
//Receiver Information
$receiverFirstName = $_POST['inputReceiverFirstName'];
$receiverLastName = $_POST['inputReceiverLastName'];
$receiverAddress = $_POST['inputReceiverAddress'];
$receiverPhone = $_POST['inputReceiverPhone'];
if(!$_POST['submit']) {
echo "Please fill out the form";
header ('Location: user.php');
}
else {
$sql = "INSERT INTO cus_sender (SenderID,StaffID,SenderFirstName,SennderLastName,Address,Phone,SEX,Age,Time)
VALUES (NULL,NULL,:firstName,:lastName,:address,:mobileNumber,:gender,:age,'')";
$sql2= "INSERT INTO package(PID,SenderID,StaffID,PackageName,PackageWeight,Price,DepartureTown,DeliveryTown,DeliveryMethod)
VALUES (NULL,NULL,NULL,:PackageName,:PackageWeight,:PackagePrice,:DepartureDestination,:finalDestination)"; //Add delivery option
$q = $db->prepare($sql);
$q->execute(array(':firstName'=>$firstName,
':lastName'=>$lastName,
':address'=>$address,
':mobileNumber'=>$mobileNumber,
':gender'=>$gender,
':age'=>$age));
$q2 = $db->prepare($sql2);
$q2->execute(array(':PackagePrice'=>$PackageName,
':PackageWeight'=>$PackageWeight,
':PackagePrice'=>$PackagePrice,
':DepartureDestination'=>$DepartureDestination,
':finalDestination'=>$finalDestination));
//':DeliveryOption'=>$DeliveryOption)); To be added later
echo "<p>Customer has been added!</p>";
header ('Location: http://localhost/BNW/newCustomer.php');
}
?>
By this way you can insert values in more than one table with single query.
<?php
$db = new mysqli('localhost', 'user', 'pass', 'test');
$start = microtime(true);
$a = 'a';
$b = 'b';
$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)');
$sql->bind_param('ss', $a, $b);
for($i = 0; $i < 10000; $i++)
{
$a = chr($i % 1);
$b = chr($i % 2);
$sql->execute();
}
$sql->close();
echo microtime(true) - $start;
$db->close();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.