Home > other >  Insert random data to database from an html input
Insert random data to database from an html input

Time:06-20

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>

CodePudding user response:

If the database operations are performed only once in the execution of this script then there is no need to instantiate functions. Simply get the number of names to insert, then insert them, using PHP prepared statements, of course, to prevent submission of inappropriate values.

<?php

include "connection.php"; // needs to provide $mysqli
$number = ""; // default empty string for form value

// perform database operations first
if (!empty($_POST["number"]) && 0 < $_POST["number"]) { // qualify input

    $number = $_POST["number"];

    // Select random data
    $get_names_stmt = $mysqli->prepare("SELECT data_firstname, data_lastname FROM data ORDER BY RAND() LIMIT ?");
    $get_names_stmt->bind_param("i", $number); // integer, value
    $get_names_stmt->execute();
    $get_names_stmt->bind_result($firstname, $lastname) // bind results to variables $firstname and $lastname

    // Prepare to insert random data
    $insert_names_stmt = $mysqli->prepare("INSERT INTO students (student_firstname, student_lastname) VALUES (?, ?)");

    // bind to string variables $firstname and $lastname
    $insert_names_stmt->bind_param("ss", $firstname, $lastname); 

    // loop random data selection, which provides variables $firstname and $lastname
    while ($get_names_stmt->fetch()) {
        // insert variables $firstname and $lastname
        $insert_names_stmt->execute();
    }

   echo "You generated " . htmlspecialchars($number) . " new students !";  
}

// if there is a $_POST["number"] variable, but it is not greater than 0
} else if (!empty($_POST["number"])) {   
    echo "Psss, try with a number greater than " . htmlspecialchars($_POST["number"] . ".");
}

?>

<form action="index.php" method="post">
    <input type="number" name="number" min="0" value="<?=$number?>"></input>
    <button type="submit" name="submit">Send</button>
</form>

By the way, FORM === client-side, PHP === server-side:

Database injections are NEVER secured on the client—NEVER trust data sent to the server. Ever.

  • Related