How to Upload Files Into a MySQL Database Using PHP?

MYSQL is utilized for creating database for websites and web applications. With its amazing performance, dependability and usability, MySQL has become best database option for web applications. It is freely accessible and simple to install. When the user uploads a file and tap on the upload button, the data is submitted to the server. PHP now takes the file and saves it in a folder in the project. Afterwards, it saves the text in the database together with a link pointing to the image in the folder. Now the biggest question is that how to upload files to MySQL database using PHP? Let’s learn.

Phase 0: Creating A Database
The process of creating database is easy. One table with a Binary large object (BLOB) field for the file data and some fields for different pieces of information relating to the file:

1. CREATE TABLE `file` (
2. `id` Int Unsigned Not Null Auto_Increment,
3. `name` VarChar(255) Not Null Default Untitled.txt,
4. `mime` VarChar(50) Not Null Default text/plain,
5. `size` BigInt Unsigned Not Null Default 0,
6. `data` MediumBlob Not Null,
7. `created` DateTime Not Null,
8. PRIMARY KEY (`id`)
9. )

As you see, a file is stored by their, including the extension. We have the mime type, which is used to let the browser know what kinds of file are dealing with. us The size of the file in bytes. And finally the data itself, in a MediumBlob field.

Phase 1: Uploading The File
Now, there is need to get the file from the user. The table we designed does not want further information from the user. So, we will make this easy and create a HTML form with only a single "file" input field and a submit button:

1. <!DOCTYPE html>
2. <head>
3. <title>MySQL file upload example</title>
4. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5. </head>
6. <body>
7. <form action="add_file.php" method="post" enctype="multipart/ form-data">
8. <input type="file" name="uploaded_file"><br>
9. <input type="submit" value="Upload file">
10. </form>
11. <p>
12. <a href="list_files.php">See all files</a>
13. </p>
Now look at the above mentioned code and you can see the third attribute of the <form> element, "enctype". This tells the browser how to send the form data to the server. As it is, when sending files, this require to be set to "multipart/form-data".
In the event that it is set any other way, or not set at all, your file is presumably not going to be transmitted accurately.

Phase 2: Add The File To The Database
As you can see in phase 1, we set the action property to "add_file.php". This is the file we are going to build it this phase of the process.

This file needs to check if a file has been uploaded, ensure that it was uploaded without errors, and add it to the database:

1. <?php
2. // Check if a file has been uploaded
3. if(isset($_FILES[uploaded_file])) {
4. // Make sure the file was sent without errors
5. if($_FILES[uploaded_file][error] == 0) {
6. // Connect to the database
7. $dbLink = new mysqli(, user, pwd, myTable);
8. if(mysqli_connect_errno()) {
9. die("MySQL connection failed: ". mysqli_connect_error());
10. }
12. // Gather all required data
13. $name = $dbLink->real_escape_string($_FILES[uploaded_file] [name]);
14. $mime = $dbLink->real_escape_string($_FILES[uploaded_file] [type]);
15.$data=$dbLink->real_escape_string(file_get_contents($_FILES [uploaded_file][tmp_name]));
16. $size = intval($_FILES[uploaded_file][size]);
18. // Create the SQL query
19. $query = "
20. INSERT INTO `file` (
21. `name`, `mime`, `size`, `data`, `created`
22. )
23. VALUES (
24. {$name}, {$mime}, {$size}, {$data}, NOW()
25. )";
27. // Execute the query
28. $result = $dbLink->query($query);
30. // Check if it was successful
31. if($result) {
32. echo Success! Your file was successfully added!;
33. }
34. else {
35. echo Error! Failed to insert the file
36. . "<pre>{$dbLink->error}</pre>";
37. }
38. }
39. else {
40. echo An error occurred while the file was being uploaded.
41. . Error code: . intval($_FILES[uploaded_file] [error]);
42. }
44. // Close the mysql connection
45. $dbLink->close();
46. }Now, using this summary as a guide, lets start writing our program.

Phase 3: Listing All Existing Files
So, now that here is few of files in our database, we have to make a list of files and link them so they can be downloaded:

1. <?php
2. // Connect to the database
3. $dbLink = new mysqli(, user, pwd, myTable);
4. if(mysqli_connect_errno()) {
5. die("MySQL connection failed: ". mysqli_connect_error());
6. }
8. // Query for a list of all existing files
9. $sql = SELECT `id`, `name`, `mime`, `size`, `created` FROM `file `;
10.$result = $dbLink->query($sql);
12.// Check if it was successful
13.if($result) {
14. // Make sure there are some files in there
15. if($result->num_rows == 0) {
16. echo <p>There are no files in the database</p>;
17. }
18. else {
19. // Print the top of a table
20. echo <table width="100%">
21. <tr>
22. <td><b>Name</b></td>
23. <td><b>Mime</b></td>
24. <td><b>Size (bytes)</b></td>
25. <td><b>Created</b></td>
26. <td><b>&nbsp;</b></td>
27. </tr>;
29. // Print each file
30. while($row = $result->fetch_assoc()) {
31. echo "
32. <tr>
33. <td>{$row[name]}</td>
34. <td>{$row[mime]}</td>
35. <td>{$row[size]}</td>
36. <td>{$row[created]}</td>
37. <td><a href=get_file.php? id={$row[id]}>Download</a></td>
38. </tr>";
39. }
41. // Close table
42. echo </table>;
43. }
45. // Free the result
46. $result->free();
50. echo Error! SQL query failed:;
51. echo "<pre>{$dbLink->error}</pre>";
54.// Close the mysql connection

Phase 4: Downloading A File
To truly see how this functions, you should see how your browser downloads documents. When a browser asks for a file from an HTTP server, the server reaction will incorporate information on what precisely it contains. These bits of information are called headers. The headers ordinarily incorporate information on the sort of data being sent, the size of the reaction, and in case of files, the name of the file.

Now, this code. We begin simply by reading the ID sent by the link in phase 3. If the ID is valid, we fetch the information on the file whose ID we received, send the headers, and finally send the file data:

1. <?php
2. // Make sure an ID was passed
3. if(isset($_GET[id])) {
4. // Get the ID
5. $id = intval($_GET[id]);
7. // Make sure the ID is in fact a valid ID
8. if($id <= 0) {
9. die(The ID is invalid!);
10. }
11. else {
12. // Connect to the database
13. $dbLink = new mysqli(, user, pwd, myTable );
14. if(mysqli_connect_errno()) {
15. die("MySQL connection failed: ". mysqli_connect_error ());
16. }
18. // Fetch the file information
19. $query = "
20. SELECT `mime`, `name`, `size`, `data`
21. FROM `file`
22. WHERE `id` = {$id}";
23. $result = $dbLink->query($query);
25. if($result) {
26. // Make sure the result is valid
27. if($result->num_rows == 1) {
28. // Get the row
29. $row = mysqli_fetch_assoc($result);
31. // Print headers
32. header("Content-Type: ". $row[mime]);
33. header("Content-Length: ". $row[size]);
34. header("Content-Disposition: attachment; filename =". $row[name]);
36. // Print data
37. echo $row[data];
38. }
39. else {
40. echo Error! No image exists with that ID.;
41. }
43. // Free the mysqli resources
44. @mysqli_free_result($result);
45. }
46. else {
47. echo "Error! Query failed: <pre>{$dbLink- >error}</pre>";
48. }
49. @mysqli_close($dbLink);
50. }
52.else {
53. echo Error! No ID was passed.;

Final Words
So, you can see file uploading process is not complex as we think. Simply think about the above-mentioned steps, and you can easily upload any kind of file in Mysql database using PHP.

Author bio: Morris Edwards is Web developer & Marketing strategist at Awebstar - A leading  web design & development company in singapore. They have built over 400+ Professional & ecommerce websites for their worldwide clients.

5 Easy Ways you can Turn Artificial Intellgence into a Success

Amongst the analysts like Gartner, Forrester and IDC, Artificial Intelligence dominates their predictions for the future. You may well ask, 'what is artificial intelligence?'. The answer to this question is as under:

What is Artificial Intelligence?
Amongst the analysts like Gartner, Forrester and IDC, Artificial Intelligence dominates their predictions for the future. You may well ask, 'what is artificial intelligence?'. The answer to this question is as under:

"Artificial Intelligence is when a machine starts behaving like a human being" Technologically, machines do not have any intelligence and they just obey the commands given by their masters. However, when machines start displaying natural intelligence, then that is called artificial intelligence. In technical words, 'any machine that judges its environment and takes action to optimize its chance of achieving its goals. Colloquially speaking, when a machine mimics the cognitive functions of a human being, then the machine is said to have artificial intelligence.

Five easy ways in which you can turn Artificial Intelligence into a success
This paragraph will talk about five easy ways artificial intelligence can be made a success. Although analysts predict the future as being full of artificial intelligence, none of the organizations of repute has yet been able to use AI to their advantage. AI is not really a new technology. Inspite of this, only 20% of CIOs report implementing AI in their organizations. Moreover, only 4 percent of organizations in totality have reported successful AI implementation. Why this step-fatherly treatment towards AI? You will be surprised to know that there are hardly any organizations, which have reported successful AI implementations. We can do the following to make AI a success:

a.    Identify competitive advantage
With every new technology that comes into the market, the technology cart gets ahead of the business value horse. However, business value eventually regains its primacy. AI is also similar. The same thing will happen in the case of AI. Gartner has advised CIOs to treat AI as they would do any other new technology and try to derive a competitive advantage out of it. This can be done by achieving a business and IT collaboration to give a competitive advantage to their organization. Thus, in order to make AI implementation a success, organizations need to understand their competitive advantage.

b.    Select the most suitable AI application

The next step is to shortlist the AI applications that will help you get your desired outcome. This is very difficult considering that McKinsey has shortlisted 600 distinct AI applications which can be useful in several industries. Please be aware that AI is not a business panacea. From AI, you need to select five applications, which will help you in your business and then select two to three from them as pilots. From the runs of the pilots, you can single out one application, which you can use further for your business. This should help you meet your business objectives and help you service your customers too.

c.    Procure AI Technology

Next, you need to find the right AI Technology to power your AI application. However, instead of looking for AI technology to power your application, you can latch on to cloud based platforms like Amazon Web Services Machine Learning or Google Cloud AI and Microsoft Azure Machine Learning. These will support your AI application and help you gain a competitive advantage. Further, you do not need to build your own AI application. You can procure software with AI inside. Today, almost all applications embed AI automatically into them to identify data relationships, patterns and recommend visualizations.

d.    Develop AI skills
Impart training to your staff in using AI. When you decide to build an AI application or work with an AI integrated machine, your staff will require to be trained in handling such applications. Encourage them to take up online courses on sites like Udemi, Udacity or edX. This will go a long way in helping them work better. With this training, they will also become more loyal to you as you have trained them in working better. Moreover, they can latch on to community support available on the Artificial Intelligence Forum, where a number of AI users congregate.

e.    Build on your success
Someone has said, "True happiness comes from the joy of deeds done well and the zest of creating things new". Therefore, as soon as you complete your first AI application, try celebrating the occasion. Take the advantages of the AI application to the lowest common denominator of your company. Do this through a case study. You can also use the marketing capability of your AI vendor to impress upon your other employees about AI.  Once you have built more applications using AI, you can always think of patenting your technology. Thus, here you are building on your success and protecting yourself by applying for a patent.

Thus, the promise made in the first paragraph of this article is fulfilled.  Five ways of making your AI a success have been elaborated in the above paragraphs. These ways may be adopted together or bit by bit, the onus rests with you.

Author Bio:

Sunny Chawla is a Marketing Manager at AIS Technolabs – a Web design and Development Company. Helping global businesses with unique and engaging tools for their business. He would love to share thoughts on Ecm Services, Web Designing and Java Web Development.