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.
Let’s coding now,
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>
In the above code we have used the PDO for database connection and execute the query.
Now, we have learned how to save text file in database using php. So, we can process the text files in PHP as we want.
Recommended:
How to secure form submission in PHP
For more PHP Tutorials visit this.
If you like this, share this.