[英]How can I insert a lot of records into database all at once from a textarea where every line of it is a record?
I'm running a website aimed for medical students, I have a profile and points for every student in my database, So when they participate in an activity I must add X amount of points for all the participants, and I do this manually using an ajax form, How can I run a MySQL query to give X amount of points for each student in a large text input (textarea)?我正在运行一个针对医学生的网站,我的数据库中的每个学生都有个人资料和积分,所以当他们参与一项活动时,我必须为所有参与者添加 X 点数,我使用手动执行此操作ajax 表格,如何运行 MySQL 查询以在大文本输入 (textarea) 中为每个学生提供 X 点数? So I can insert the points all at once which is much easier and faster, Here is an example:所以我可以一次插入所有点,这更容易更快,这是一个例子:
21910431|1|Participant
22010431|3|Subleader
21810531|6|Headleader
(Student ID)|(points)|(role in activity)
So when I fill the textarea with the data above it must insert 3 records into the activity_log
table.因此,当我用上面的数据填充 textarea 时,它必须在activity_log
表中插入 3 条记录。 How can I insert this into the database all at once?如何一次将其全部插入数据库? Like this:像这样:
$query= "INSERT INTO `activity_log` (`Student ID`, `points`, `role`) VALUES (ALL THE VALUES IN THE EXAMPLE ABOVE)";
If anyone can help can you write the code to show me how?如果有人可以帮助您编写代码来告诉我如何操作吗? Thanks alot!非常感谢!
You can insert multiple rows:您可以插入多行:
INSERT INTO `activity_log` (`Student ID`, `points`, `role`) VALUES (21910431,1,'Participant'),(22010431,3,'Subleader'),...;
Using placeholders, this would be:使用占位符,这将是:
INSERT INTO `activity_log` (?,?,?),(?,?,?),...;
just passing all the values to execute.只是传递所有值来执行。
Using PDO:使用 PDO:
$lines = explode("\n", $_POST['textarea']); // split into lines
$params = [];
foreach ($lines as $line) {
if ($line) { // skip blank lines
$params += explode('|', $line); // split each line into individual values
}
}
# Make all the (?, ?, ?) that go after VALUES
$values = implode(',', array_fill(0, count($params)/3, '(?, ?, ?)'));
$query= "INSERT INTO `activity_log` (`Student ID`, `points`, `role`) VALUES $values";
$stmt = $conn->prepare($query);
$stmt->execute($params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.