我有一张桌子' prac1'列id ( primary key, auto_increment)
,Name
和Contact
。另一张桌子' prac2'列id(foreign key)
,Order_id(primary key)
和Order_items
。
<?php
$ok=isset($_POST['ok']);
if($ok)
{
$name=$_POST['cname'];
$order=$_POST['oi'];
$contact=$_POST['contact'];
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("INSERT INTO prac1 (Name,Contact) values (?,?)");
$stmt->bind_param("si",$name,$contact);
$stmt->execute();
$stmt=$db->prepare("INSERT INTO prac2 (Order_items) values(?) ");
$stmt->bind_param("i",$order);
$stmt->execute();
}
?>
<form action="prac.php" method="POST">
Name:<input type="text" name="cname"><br>
Contact:<input type="text" name="contact"><br>
Order Items:<input type="text" name="oi"><br>
<input type="submit" name="ok"><br>
现在,从此表单提交中,名称和订单项将插入到相应的表中,并在表prac1中使用自动递增ID。如何检索表prac1的id以插入到prac2中。 我想因为prac2表中的NULL id,两个表没有连接,下面的代码不显示任何内容。
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM prac1 INNER JOIN prac2 ON prac1.id=prac2.id ORDER BY prac2.Order_items");
$stmt->execute();
$result=$stmt->get_result();
echo "<TABLE BORDER='1'>";
echo "<tr><thead><td>ID</td><td>Order ID</td><td>Order items</td><td>Name</td><td>Contact</td><td>Status</td></thead></tr>";
while($row=$result->fetch_assoc())
{
echo "<tr>";
echo "<td>";
echo $row['id'];
echo "</td><td>";
echo $row['order_id'];
echo "</td><td>";
echo $row['Order_items'];
echo "</td><td>";
echo $row['Name'];
echo "</td><td>";
echo $row['Contact'];
echo "</td><td>";
echo $row['Status'];
echo "</td>";
echo "</tr>";
}
echo "</table>";
答案 0 :(得分:1)
你走了:
<?php
if( isset($_POST['ok']) ) {
$name = $_POST['cname'];
$order = $_POST['oi'];
$contact = $_POST['contact'];
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("INSERT INTO prac1 (Name, Contact) values (?,?)");
$stmt->bind_param("si",$name,$contact);
$stmt->execute();
//HERE YOU GET THE INSERT ID
$insertID = $db->insert_id; //THIS IS THE ID THAT YOU NEED ...
// OR IF YOU ARE INTO PROCEDURAL STYLE:
// $conn = mysqli_connect("localhost", "my_user", "my_password", "world");
// YOU CAN DO THIS:
// $insertID = mysqli_insert_id($conn)
//THE REST OF YOUR CODE
$stmt=$db->prepare("INSERT INTO prac2 (Order_items) values(?) ");
$stmt->bind_param("i", $insertID);
$stmt->execute();
}
希望这有点帮助...