-1

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>
Garfaz
  • 47
  • 5
  • Cast the post as (int) everywhere... You are open to so many exploits right now.. – Ron Jun 19 '22 at 09:00
  • 1
    There seem to be several disparate issues, although in your question you didnt mention any specific errors or even give a clear provlem statement ("not able to" doesn't explain anything). From a quick glance, insertData() clearly requires to parameters which you haven't passed in. selectData() appears not to exist at all. $number is not used anywhere - perhaps you intended to use that in a LIMIT clause in your SELECT? And you're vulnerable to sql injection and syntax errors in your insert query ...always use prepared statements and parameters. – ADyson Jun 19 '22 at 09:12
  • Oh and $dataRow will get overwritten every time in your while loop so you'll only ever return the last row found by the query...you need to run one insert per row returned, so either call it from within the loop, or make an array of all the rows, return that array, and then loop through that separately to run the inserts. Overall it seems this code needs a thorough review from you, some more attention to detail paying. and some proper debugging. Also Google the "rubber duck debugging" technique, I think it would probably benefit you to use it. – ADyson Jun 19 '22 at 09:17
  • And unless you've omitted some stuff, `value="{$row['number']}"` doesn't appear to make much sense, we cannot see $row defined or populated anywhere. – ADyson Jun 19 '22 at 09:21
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jun 19 '22 at 19:02
  • Did you mean to say "not working"? If so, in what way? – Rick James Jun 23 '22 at 17:15
  • Consider `ORDER BY RAND() LIMIT n` – Rick James Jun 23 '22 at 17:15

1 Answers1

1

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->store_result(); // allows simultaneous insert
    $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();
    }

    // wrap it all up
    $get_names_stmt->close();
    $insert_names_stmt->close();
    $mysqli->close();

    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.

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37