我尝试使用一个表单将数据插入到两个单独的mysql表中。
在下面的php代码中,我有两个insert语句,一个用于表游戏,一个用于表结果。如果我单独使用“insert into games…”或“insert into results…”语句运行代码(修改corse表单,使其仅包含相应的一个或两个相应字段),数据将正确插入数据库。当我试着同时做的时候,我就不知道我做错了什么。请注意,当我在phpmyadmin中同时运行两个insert语句时,数据会正确地插入到两个表中。
我已经阅读了mysqli\u multi\u query并尝试了各种选项来使用它,但是没有任何结果,因为我不知道如何将它与下面的prepare语句一起使用。
if($stmt = mysqli_prepare($link, $sql))
以下是php部分:
<?php
// Define variables and initialize with empty values
$tourn_id = "";
$game_id = "";
$player_id = "";
$tourn_name_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check input errors before inserting in database
if(empty($tourn_name_err)){
// Prepare an insert statement
$sql = "INSERT INTO Games (idTournaments) VALUES (?);
INSERT INTO Results (idGames, idPlayers) VALUES (?, ?);";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iii", $param_tourn_id, $param_game_id, $param_player_id);
// Set parameters
$param_tourn_id = trim($_POST["tourn_id"]);
$param_game_id = trim($_POST["game_id"]);
$param_player_id = trim($_POST["player_id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: welcome.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
下面是html表单部分:
<div class="wrapper">
<form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<h1 class="form-signin-heading">New Match</h1>
<div class="form-group <?php echo (!empty($tourn_name_err)) ? 'has-error' : ''; ?>">
<label>Enter Tournament ID here ...:</label>
<input type="number" name="tourn_id"class="form-control" value="<?php echo $tourn_id; ?>">
<span class="help-block"><?php echo $tourn_name_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($tourn_name_err)) ? 'has-error' : ''; ?>">
<label>Enter Game ID here ...:</label>
<input type="number" name="game_id"class="form-control" value="<?php echo $game_id; ?>">
<span class="help-block"><?php echo $tourn_name_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($tourn_name_err)) ? 'has-error' : ''; ?>">
<label>Enter Player ID here ...:</label>
<input type="number" name="player_id"class="form-control" value="<?php echo $player_id; ?>">
<span class="help-block"><?php echo $tourn_name_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</form>
</div>
1条答案
按热度按时间roejwanj1#
好的,在多次尝试错误并去掉原始php代码中的“prepare语句”之后,它开始工作了。我还尽可能地遵循手册中的mysqli\u multi\u查询示例。
我不确定像下面这样设置参数是否必要。
下面是完整的php代码: