DEV Community

Cover image for How to save text file in database using PHP?
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at w3courses.org

How to save text file in database using PHP?

In PHP we can process the file as many ways like uploading image file, processing video file, uploading audio file, saving a zip file etc. Sometimes we needs to get and save the data from text file also. So, here we will learn how to save text file in database using PHP.

We will simple use $_FILES array, get the contents from it and explode the contents. Then gets the data line by line using foreach loop and finally save the data in database.

Simply create a file save.php, paste the code given below and run the file at your localhost or server.

<?php
/*database connection*/
$host = 'localhost';
$dbname = 'file_in_db';
$username = 'root';
$password = '';

$conn = new PDO('mysql:host='.$host.';dbname='.$dbname,$username,$password);
/*database connection*/

/*submit form*/

$success = $error = '';

if (isset($_POST['submit']) && $_POST['submit'] == 'Submit') {

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        $content = file_get_contents($_FILES['file']['tmp_name']);

        $content = explode("\n", $content);

        foreach ($content as $key => $value) {

            try{

                $currentDate = date('Y-m-d H:i:s');

                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $sql = 'INSERT INTO `emails`(email,created_at) VALUES("'.$value.'", "'.$currentDate.'")';

                $conn->exec($sql);

                $success = 'Email Inserted';

            }catch(PDOException $e){
                $error = 'All Emails Not Inserted';
                echo $sql.'<br>'. $e->getMessage();
            }

        }

    }
}

/*submit form*/


?>

<!DOCTYPE html>
<html>
<head>
    <title>Save Text File in Database</title>
    <style type="text/css">
        .success{
            color: green;
        }
        .error{
            color: red;
        }
    </style>
</head>
<body>

    <center>
        <?php if($success): ?>
            <h3 class="success"><?php echo $success; ?></h3>
        <?php endif; ?>

        <?php if($error): ?>
            <h3 class="error"><?php echo $error; ?></h3>
        <?php endif; ?>
    </center>

    <center>
        <h1>Save Text File in Database</h1>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="file"/>

            <input type="submit" name="submit" value="Submit">
        </form>
    </center>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the above code we have used the PDO for database connection and execute the query.

Please like share and give positive feedback to motivate me to write more

For more tutorials visit my website.

Thanks:)
Happy Coding:)

Top comments (4)

Collapse
 
lito profile image
Lito

Please, check your code before send your posts. This code include bad practices and SQL injections. People learning PHP can create a lot of security problems using your code.

<?php
/*database connection*/
$host = 'localhost';
$dbname = 'file_in_db';
$username = 'root';
$password = '';

$pdo = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$errors = null;

if (!empty($_FILES['file']['tmp_name'])) {
    $content = file($_FILES['file']['tmp_name'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $date = date('Y-m-d H:i:s');
    $errors = [];

    $query = $pdo->prepare('INSERT INTO `emails` (`email`, `created_at`) VALUES (?, ?);');

    foreach ($content as $email) {
        try {
            $query->execute([$email, $date]);
        } catch (PDOException $e) {
            $errors[] = 'Error adding email: '.$e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Save Text File in Database</title>
    <style type="text/css">
        .success{
            color: green;
        }
        .error{
            color: red;
        }
    </style>
</head>
<body>
    <?php if (is_array($errors)) { ?>
    <center>
        <?php if (empty($errors)) { ?>
        <h3 class="success">Emails imported successfully</h3>
        <?php } else { ?>
        <h3 class="error"><?= implode(', ', $errors); ?></h3>
        <?php } ?>
    </center>
    <?php } ?>

    <center>
        <h1>Save Text File in Database</h1>

        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="file"/>
            <input type="submit" name="submit" value="Submit">
        </form>
    </center>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
readymadecode profile image
Chetan Rohilla • Edited

Here we are not validating, sanitizing data or file, just processing text file. For security we have written a separate article, will share here soon. Can you please suggest some options here. It would be great to share your knowledge.
Thanks:)

Collapse
 
lito profile image
Lito

Security is a MUST in code development, not an extra or an option. You can not write an insecure article as this and say that is not about security, it has not sense. You are sharing your bad practices to all new PHP developers. THIS is why a lot of developers say that PHP is insecure, because a lot of developers write insecure code and share it as right.

There are a lot of errors with your code:

  • You are reading a file from $_FILES['file']['tmp_name'] and can be empty.
  • Setting $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); on every line iteration. You only need to do one time.
  • You are not checking empty lines.
  • Email content is added as string inside query instead using prepare and execute. THIS IS A TERRIBLE BAD IDEA. Read more about SQL injections.

You should fix your article or you will be reported, sorry.

Thread Thread
 
readymadecode profile image
Chetan Rohilla

Thanks! Bro for your kind positive suggestions. I will definitely apply and will post here. That's we all developers always needs to share some knowledge between us.

Thanks:)