我想获取movie和actor表的主键值。当我在单选按钮中选择值时,主键已自动创建到影片和actor表中。现在我想获得该主键值并插入到movie_actor表中。 我的代码
connect.php
<?php
$dbc = mysqli_connect('localhost','root','black98765','db_name')
OR die("Cannot connect to MySQL:" . mysqli_connect_error());
//insert into actor table
$q = "INSERT INTO actor (name)
VALUES ('$actor')";
//execute the query to get primary key value
$r = mysqli_query($dbc,$q);
//assign to variable below
$actor_no = mysqli_insert_id($dbc);
//insert into movie table
$q2 = "INSERT INTO movie (movie_name, release_year)
VALUES ('$movie','$year')";
//execute the query to get primary key value
$r2 = mysqli_query($dbc,$q2);
//assign to variable below
$movie_no = mysqli_insert_id($dbc);
$q3 = "INSERT INTO movie_actor (movie_no, actor_no, rate)
VALUES ($movie_no, $actor_no, '$rate')";
//connect and insert $q
$r3 = mysqli_query($dbc,$q3);
if($r && $r2 && $r3){
echo "Inserted Successfully!";
}else{
echo "Failed to Insert Data!";
mysqli_error($dbc);
}
mysqli_close($dbc);
?>
form.php
<?php
if(isset($_POST['submit'])){
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$error = array();
//choose actor
if(!isset($_POST['actor'])){
$error[] = "Please choose of the following actors!";
}else{
$actor = $_POST['actor'];
}
//choose movie
if(!isset($_POST['movie'])){
$error[] = "Please choose of the following movies!";
}else {
$movie = $_POST['movie'];
}
//choose release year
if(!isset($_POST['year'])){
$error[] = "Please choose of the following release year!!";
}else{
$year = $_POST['year'];
}
//choose rate
if(!isset($_POST['rate'])){
$error[] = "Please choose of the following rate!";
}else{
$rate = $_POST['rate'];
}
//if no errors
if(empty($error)){
require('connect.php');
}else{
echo "<p>System Error!</p>";
foreach($error as $msg){
echo $msg."<br/>\n";
}
}
}
}
&GT;
<form action="form.php" method="POST">
<p>Select on the following Selections</p>
<p><label for="actor">Name of Actor:</label>
<input type="radio" name="actor1" value="Jet Li"/>Jet Li
<input type="radio" name="actor2" value="Sylvester Stallone"/>Sylvester Stallone
<input type="radio" name="actor3" value="Jason Statham"/>Jason Statham</p>
<p><label for="movie">Name of Movie:</label>
<input type="radio" name="movie1" value="Expendables 3"/>Expendables 3
<input type="radio" name="movie2" value="Rocky"/>Rocky
<input type="radio" name="movie3" value="Kiss of the Dragon"/>Kiss of the Dragon</p>
<p><label for="movie">Release Year:</label>
<input type="radio" name="year1" value="2014"/>2014
<input type="radio" name="year2" value="1976"/>1976
<input type="radio" name="year3" value="2001"/>2001</p>
<p><input type="submit" name="submit" value="Insert"/></p>
</form>