I'm trying to create a function to insert one or more randomly generated row(s) of data into a table.
Here is an exemple:
On my index, there is an input field where the user can only submit a number.
When the query is submitted, my application selects a random data into a dedicated table. Then, according to the submitted number, my function should insert data row(s) according to the submited number.
Those data I am talking about are firstnames and lastnames. So, if I submit into the input, let's say the number 5 (it can also be another number), then php must insert 5 rows of firstnames and lastnames into my table.
The code is now working.
INPUT
<?php
include "connection.php";
// Obtention des entrées de l'input
if (!empty($_POST["input"]) && 0 < $_POST["input"]) { // Si input n'est pas vide et supérieur à 0
$input_value = intval($_POST["input"]); // $_POST["input"] est attribué à une variable: $input_value
for ($i = 0; $i < $input_value; $i++) {
// Sélection d'un élève au hasard
$get_names_stmt = $mysqli->prepare("SELECT data_firstname, data_lastname FROM data ORDER BY RAND (?) LIMIT 1");
$get_names_stmt->bind_param('i', $input_value); // ("i" = integer, "$input_value" = valeur de l'entrée) La valeur de l'entrée est un integer
$get_names_stmt->execute();
$get_names_stmt->bind_result($firstname, $lastname); // Les résulats sont assignés aux variables $firstname et $lastname
$get_names_stmt->store_result();
$insert_names_stmt = $mysqli->prepare("INSERT INTO students (student_firstname, student_lastname) VALUES (?, ?)");
$insert_names_stmt->bind_param("ss", $firstname, $lastname); // ("ss" = deux string, "$firstname" = data_firstname, "$lastname" = data_lastname) Les deux variables sont des strings
while ($get_names_stmt->fetch()) {
$insert_names_stmt->execute();
}
}
}
header("Location:../index.php");
INDEX
<?php
include "inc/connection.php";
include "inc/truncate.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Generator</title>
</head>
<body>
<!-- Bouton truncate -->
<form action="inc/truncate.php" method="post">
<button type="submit" name="truncate">Reset</button>
</form>
<form action="inc/input.php" method="post">
<input type="number" name="input" min="0" required></input>
<button type="submit" name="submit">Send</button>
</form>
</body>
</html>