php mysqli将多行插入到一个表中,并将一行插入到另一个表中
在这个网站的帮助下,我一直在做这件事。我现在可以在php mysqli将多行插入到一个表中,并将一行插入到另一个表中,php,mysql,mysqli,Php,Mysql,Mysqli,在这个网站的帮助下,我一直在做这件事。我现在可以在players表中插入多行(基于$addrows值)。我还需要在事件中插入表1行。当我提交表单时,它会插入playersfine,但不会插入events 这是我的表单,包含2个查询所需的所有值 <form id="form-add" name="form-add" method="POST" enctype="multipart/form-data" action="page.php"> <input name="add-nam
players
表中插入多行(基于$addrows
值)。我还需要在事件中插入表1行。当我提交表单时,它会插入players
fine,但不会插入events
这是我的表单,包含2个查询所需的所有值
<form id="form-add" name="form-add" method="POST" enctype="multipart/form-data" action="page.php">
<input name="add-name" id="add-name" type="text" value="Event">
<input name="add-start" id="add-start" type="text" value="">
<input name="add-end" id="add-end" type="text" value="">
<input name="add-loc" id="add-loc" type="text" value="">
<input name="add-rows" id="add-rows" type="text" value="">
<input name="add-submit" id="add-submit" type="submit" value="Add" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
这些是我在表单中发布的值
<?php
$add_name = $_POST['add-name'];
$add_start = $_POST['add-start'];
$add_end = $_POST['add-end'];
$add_loc = $_POST['add-loc'];
$add_rows = $_POST['add-rows'];
$add_url = date('Y-m-d',strtotime($add_start)).'-'.str_replace('-',' ',($add_name));
if(isset($_POST['submitted'])) { //check if form submitted
//connection
$mysqli = new mysqli('host', 'user', 'pass', 'db_name');
//this is the first query - to insert multiple rows in to players table (from same form)
$query = "INSERT INTO players (position, event, start, end, name, one, two, three, four, five, six)
VALUES ('', '$add_url', '$add_start', '$add_end', '', 'Yes', 'No', 'No', 'No', 'No', 'No');" .
str_repeat(", ('', '$add_url', '$add_start', '$add_end', '', 'Yes', 'No', 'No', 'No', 'No', 'No')", $add_rows - 1);
//this is the 2nd query - to insert to events table (from same form)
$query .= "INSERT INTO events (ur, name, start, end, loc) VALUES ('$add_url', '$add_name' '$add_start', '$add_end', '$add_loc');";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}//end of form submit if
?>
您的代码有3个主要错误
您使用的是mysqli\u multi\u query()
,这在这里毫无用处,只会使代码过于复杂
您没有使用占位符,这使得您的代码容易被注入
您正在数据库中插入相同的行,这违反了数据库法律李>
因此,进行2次查询:一次将1条记录插入玩家表,另一次将-1条记录插入事件。
使用准备好的语句在两个单独的调用中运行它们。
由于mysqli不能与它们一起使用,因此请改用PDO @你的常识我需要输入x行数bcz没有名称(玩家表中的名称列)。这些将在稍后更新。但需要x个插槽(行)。关于multi_查询,我尝试过,但没有成功。我可以插入球员表,但不能插入事件。我现在正在检查我的代码。。按照你的建议进行调试,但还不走运。谢谢