这是确切的情景
当我填写日期和备注时,我点击它应该插入我的数据库中的添加按钮。
这是我的PHP脚本我知道它有问题。
<?php
require("config.inc.php");
if(!empty($_POST)){
if(empty($_POST['date']) || empty($_POST['remark'])){
$response["Success"] = 0;
$response["Message"] = "Please complete all fields.";
die(json_encode($response));
}
$query = "SELECT 1 FROM tb_attendance WHERE date = :date";
$query_params = array(
':date'=> $_POST['date'],
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
$response["Success"] = 0;
$response["Message"] = "Database Error. Please Try Again...";
die(json_encode($response));
}
$row = $stmt->fetch();
if($row){
$response["Success"] = 0;
$response["Message"] = "I'm sorry, this Record is already existed.";
die(json_encode($response));
}
$query = "INSERT INTO tb_attendance (date, remark) VALUES(:date, :remark)";
$query_params = array(
':date' => $_POST['date'],
':remark' => $_POST['remark']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
$response["Success"] = 0;
$response["Message"] = "Database Error1. Please Try Again...";
die(json_encode($response));
}
$response["Success"] = 1;
$response["Message"] = "Attendance Successfully Recorded.";
echo json_encode($response);
}else{
?>
<form action="addAttendance.php" method="post">
Date: <input type="text" name="date"><br>
Remark: <input type="text" name="remark"><br>
<input type="submit">
</form>
<?php
}
?>
答案 0 :(得分:0)
只需在数组中发送帖子数据,然后使用该数组播放以创建用于插入一堆记录的查询
答案 1 :(得分:0)
尝试以下多个插入的结构
INSERT INTO `table_name` (`key1`, `key2`, `key3`, `key4`) VALUES
('val11', 'val12', 'val13', ''),
('val21', 'val22', 'val23', ''),
('val31', 'val32', 'val33', ''),
('val41', 'val42', 'val43', '');
答案 2 :(得分:0)
让我们考虑你有一个多个值的数组,如
$array = array (
0 => array(
0=>"val11",
1=>"val12",
2=>"val13",
3=>"val14"
),
1 => array(
0=>"val11",
1=>"val12",
2=>"val13",
3=>"val14"
),
2 => array(
0=>"val11",
1=>"val12",
2=>"val13",
3=>"val14"
),
3 => array(
0=>"val11",
1=>"val12",
2=>"val13",
3=>"val14"
)
)
然后你可以内爆数组的每个索引,如
foreach($array as &$value){
$value = "('".implode("', '",$value)."')"
}
这将返回一个类似
的数组$array = array (
0 => "('val11', 'val12', 'val13', 'val14')",
1 => "('val11', 'val12', 'val13', 'val14')",
2 => "('val11', 'val12', 'val13', 'val14')",
3 => "('val11', 'val12', 'val13', 'val14')"
)
然后你可以使用逗号
来内爆这个数组$array = implode (", "$array);
这会返回一个像
这样的字符串('val11', 'val12', 'val13', ''), ('val21', 'val22', 'val23', ''), ('val31', 'val32', 'val33', ''), ('val41', 'val42', 'val43', '');
你可以用
附加这个字符串INSERT INTO `table_name` (`key1`, `key2`, `key3`, `key4`) VALUES
所以你会得到完整的查询
INSERT INTO `table_name` (`key1`, `key2`, `key3`, `key4`) VALUES ('val11', 'val12', 'val13', ''), ('val21', 'val22', 'val23', ''), ('val31', 'val32', 'val33', ''), ('val41', 'val42', 'val43', '');
正如您在数组中猜到的那样,您可以拥有所需数量的记录,可以是1或100。