Skip to content
PHP Logo

How can PHP be used to randomly select data from two separate text files and insert them into a database?

To randomly select data from two separate text files and insert them into a database using PHP, you can first read the contents of the text files into arrays. Then, randomly select an element from each array and insert them into the database using SQL queries.

php
// Read the contents of the text files into arrays
$file1 = file('file1.txt');
$file2 = file('file2.txt');

// Randomly select elements from the arrays
$random1 = $file1[array_rand($file1)];
$random2 = $file2[array_rand($file2)];

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Insert the selected data into the database
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$random1', '$random2')";
$connection->query($sql);

// Close the database connection
$connection->close();