php - 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)? 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.
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!
Answer
Solution:
Using 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);
Answer
Solution:
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.
Source