J
J
Jeux_Onmobil2020-05-21 09:30:18
PHP
Jeux_Onmobil, 2020-05-21 09:30:18

How can I get data from a text file and write it to the database?

There is a form where there are: 1) Text field, 2) Input file field, 3) Button The
user enters any word in No. 1, loads the .txt file in No. 2 and clicks on the button. It is necessary to make sure that the words from the file are written to the DB column "name", and the word from No. 1 to the "home" column. There is a code, it loads one word at a time.

session_start();
require('../connection.php');

if (isset($_POST['download'])){
    $name = $_POST['name'];
    $home= $_POST['home'];
    $query = "INSERT INTO `table` (`name`, `home`) VALUES ('$name', '$home')";
    $result = mysqli_query($connection,$query);
}

header('Location: ../index.php');

Can this be done in php?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-05-21
@Jeux_Onmobil

But in general, of course, if you do it wisely, then a beginner cannot cope.
Yes, and not every average peasant will master, which is already there.

$file = file($_FILES['name']['tmp_file'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$query = "INSERT INTO `table` (`name`, `home`) VALUES (?, ?)";
$stmt = $connection->prepare($query);
$stmt->bind_param("ss", $name, $home);

$connection->begin_transaction();
foreach($file as $home) {
    $stmt->execute();
}
$connection->commit();

The file must be read, removing line breaks (and at the same time empty lines).
For queries that use variables, you should always use prepare.
Insertions that are executed in a loop must be enclosed in a transaction. For speed and in general.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question