How to Use PHP to Insert Data Into MySQL Database
Managing data within a MySQL database is crucial for web applications and websites. While there are several methods available, one powerful approach is by using PHP to interact with the database. By leveraging the capabilities of MySQLi and PHP Data Objects (PDO) extensions, users can seamlessly insert data into MySQL databases with enhanced security and performance.
In this tutorial, we will show you how to insert data into a MySQL database using PHP scripts and provide you with the necessary knowledge and techniques to effectively utilize PHP for data insertion.
Download glossary for web beginners
Create a Table for the Data
The first step is to create a table for the data. If you have already created one, scroll down to the next section. If not, follow these steps:
- Open phpMyAdmin on your hosting control panel.
- Open u123456789_mydatabase and navigate to the Create table section.
- Name the table Students and write 4 in the Number of columns field. Click the Go button near the bottom of the page.
- A new page will appear. Enter the necessary information for the table.
- Click Save to create a new table.
Here are a few explanations of the columns used:
- Name – The column name. It will appear at the top of the table.
- Type – The data type. You can set various values, including int, varchar, and string. For example, select varchar to enter a string type name, which uses letters, not numbers.
- Length/Values – The maximum entry length for a particular column.
- Index – To enumerate table entries, which is required when configuring table relationships. We recommend always having one ID column when creating a table. We used the Primary index for our ID field and marked A_I, which means Auto Increment. It automatically lists the entries (1,2,3,4…).
For more information about table structure and its available settings, refer to phpMyAdmin’s official documentation.
How to Insert Into MySQL Database Table
There are two methods to INSERT data into MySQL database – the PHP MySQLi method and the PHP Data Object (PDO) method.
Inserting Data Using MySQLi Method
First, establish a connection to a database. When connected, proceed with the INSERT MySQL query. Here is a full PHP code example with the basic connection and insert methods:
<?php $servername = "localhost"; $database = "u123456789_mydatabase"; $username = "u123456789_myuser"; $password = "PasSw0rd123@"; // Create a connection $conn = mysqli_connect($servername, $username, $password, $database); // Check the connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; $sql = "INSERT INTO Students (name, lastName, email) VALUES ('Tom', 'Jackson', 'tom@jackson.tld')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
Important! If you are setting up a database for remote use, the hosting won’t be on the same server as the database. You must set up remote MySQL access first and use its server address instead of localhost.
Lines 2-12 of the code are for the actual connection to the MySQL database. The following line looks like this:
$sql = "INSERT INTO Students (name, lastName, email) VALUES ('Tom', 'Jackson', 'tom@jackson.tld')";
The INSERT INTO is a statement that adds data to the specified MySQL database table. In the example above, we are adding data to the table Students.
Between the parenthesis, the table column names specify where we want to add the values (name, lastName, email). The script will add the data in the specified order. If we write (email, lastName, name), the script will add the values in the wrong order.
The next part is the VALUES statement. Here, we specify values in the previously selected columns. Our example would be name = Tom, lastName = Jackson, email = tom@jackson.tld.
Additionally, users must set SQL queries between quotes. In our example, everything written in quotes after $sql = is an SQL query.
Meanwhile, lines 14-15 of the code check if the query works and displays a success message:
if (mysqli_query($conn, $sql)) { echo "New record created successfully";
The final part, lines 16-18, displays a different message in case the query fails. It shows an error SQL message instead:
} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
Inserting Data Using the PHP Data Object (PDO) Method
To use this method, establish a database connection first by creating a new PDO object.
Since the connection to the MySQL database is a PDO object, you must use various PDO methods to prepare and run queries.
Methods of objects are called like this:
$the_Object->the_Method();
PDO allows users to prepare, evaluate, and correct the SQL code before executing. It can prevent a malicious person from performing a simplified SQL injection attack by typing SQL code into a form.
// User writes this in the username field of a login form
john"; DROP DATABASE user_table; // The final query becomes this "SELECT * FROM user_table WHERE username = john"; DROP DATABASE user_table;
As a syntactically correct SQL code, the semi-colon makes DROP DATABASE user_table a new SQL query and deletes the user table. Fortunately, prepared statements do not allow the “ and ; characters to end queries. Thus, a malicious instruction to DROP DATABASE would not work.
Important! You should always use prepared statements when sending or receiving data from the database with PDO.
To use prepared statements, you must write a new variable that calls the prepare() method of the database object. The result will look like this:
<?php $servername = "localhost"; $database = "u123456789_mydatabase"; $username = "u123456789_myuser"; $password = "PasSw0rd123@"; $sql = "mysql:host=$servername;dbname=$database;"; $dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; // Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object try { $my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options); echo "Connected successfully"; } catch (PDOException $error) { echo 'Connection error: ' . $error->getMessage(); } // Set the variables for the person we want to add to the database $first_Name = "Tom"; $last_Name = "Jackson"; $email = "tom@jackson.tld"; // Here we create a variable that calls the prepare() method of the database object // The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name $my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastName, email) VALUES (:first_name, :last_name, :email)"); // Now we tell the script which variable each placeholder actually refers to using the bindParam() method // First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to $my_Insert_Statement->bindParam(":first_name", $first_Name); $my_Insert_Statement->bindParam(":last_name", $last_Name); $my_Insert_Statement->bindParam(":email", $email); // Execute the query using the data we just defined // The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here if ($my_Insert_Statement->execute()) { echo "New record created successfully"; } else { echo "Unable to create record"; } // At this point, you can change the data of the variables and execute again to add more data to the database $first_Name = "John"; $last_Name = "Smith"; $email = "john.smith@domain.tld"; // Execute again now that the variables have changed if ($my_Insert_Statement->execute()) { echo "New record created successfully"; } else { echo "Unable to create record"; }
In lines 24-26, we use the bindParam() method of the database object. There is also the bindValue() method, which works differently:
- bindParam() – evaluates data when the execute() method is reached. The first time the script reaches an execute() method, it sees that $first_Name corresponds to “Tom”, binds that value, and runs the query. When the script reaches the second execute() method, it sees that $first_Name now corresponds to “John”, binds that value, and reruns the query with the new values. Note that we defined the query once and reused it with different data at different points in the script.
- bindValue() – evaluates the data as soon as bindValue() is reached. Since the value of $first_Name was set to “Tom” when the bindValue() was reached, it will be used every time an execute() method is called for $my_Insert_Statement.
Notice that we reuse the $first_Name variable and assign it a new value the second time. If you check your database after running this script, you have both defined names, despite the $first_Name variable equalling “John” at the end of the script.
The bindParam method accepts parameters by reference, not by value. Users only need to call bindParam once, and the script will insert updated values into the database.
You can read more about passing parameters in the PHP manual.
Confirming the Success
If the query that we ran and INSERT into MySQL database was successful, we would see the following message:
Connected Successfully
New record created successfully
Troubleshooting Common Errors
Sometimes, the new record will show an error with the SQL insert. Luckily, there are ways to fix these MySQL errors.
MySQLi
If a MySQLi error message appears, we can attempt various fixes.
For example, if we have one syntax error in our code, we will see the following error:
Connect successfully Error: INSERT INTO students {name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld') You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld')' at line 1"
As you can see, the first part of the code is good and the script established the connection successfully. However, the SQL query failed.
"Error: INSERT INTO Students {name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld') You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld')' at line 1"
This is because a syntax error caused the script to fail. The error was here:
$sql = "INSERT INTO Students {name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld')";
We incorrectly used curly brackets instead of simple parentheses, causing the script to throw a syntax error.
PDO
To receive error messages for troubleshooting, the user must set the error mode to display all exceptions. That’s what’s written in line 12 of the PDO connection. Since all exceptions are enabled, any specific issue will be displayed.
Users should only use all exceptions when developing a script. It can expose the database and table names, which the user should hide from malicious parties.
In the case above, where curly braces were used instead of parentheses, the error looks similar to this:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; <code>check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastName, email} VALUES ('Tom', 'Jackson', 'tom@jackson.tld')' at line 1"
Other Potential Issues:
- Specifying incorrect columns like non-existent columns or a spelling mistake.
- One type of value being assigned to another type of column. For example, if we tried to assign the number 47 to a Name column, we would get an error because it is supposed to be a string value. But if we assigned a number between quotes, for example, “47”, it would work because our number would be a string to the column.
- Accessing remote MySQL database without Remote MySQL set up.
All those errors can be easily fixed by following the error message guidelines or checking the error log.
Conclusion
PHP programming language allows users to easily add new MySQL database data with a few lines of code.
In this tutorial, we have shown how to use PHP to insert data into your MySQL database using MySQLi, INSERT statement, and PDO. We have also showcased how to troubleshoot common connection errors.
We hope that you found this tutorial useful. If you have any questions, let us know in the comments below.
Comments
September 23 2017
Hi, first and foremost, congratulations for your excellent tutorial. The only remark I feel like making is that in your tutorial it seems that it's necessary to use phpmyadmin to use PHP to Insert Data Into MySQL Database. Probably my question is naive or a bit silly and for that I do apologize; I've been studying these subjects on my own with a great passion by the way. So, please help me understand because I looked into many other tutorials on the Web without being able to find out the solution to my problem I had been looking for. Let me give you an example. I have created a form (let's suppose with a textarea to fill out with the a comment); upon filling in the whole form I wish to click on the button "submit". Let's also suppose that 1) I use php instead of Perl, Phyton and so forth. 2) I WANT to use the Maria DB SQL DATABASE MANAGEMENT SYSTEM. I should stress that, as far as I know but if I go wrong don't hesitate to correct me, MySQL is the world's most popular open-source RDBMS. It is extremely fast and is used by some of the most frequently visited Web sites on the Internet, including Google, Facebook, Twitter, Yahoo, You Tube, and Wikipedia. Recently, HOWEVER, some of these companies HAVE MOVED TO MariaDB. Fedora/RHEL HAS REPLACED MySQL in its repositories with MariaDB, and Wikipedia has also converted. Ubuntu provides both version. 3) the HTML 5, CSS 3 and all possible other files have been placed in /var/www/html on my Debian 8 remote Server (where I have set up Apache and built a Website, which for now I prefer not to write in the textbox below). 4) Now, and THIS IS THE CRUCIAL POINT I WANT TO MAKE, I wish to write a PHP script that allows me to store all the form data I submitted INTO a table of a database of MariaDB. And I want to do that without using phpmyadmin, which of course would simplify my task, I'm fully aware of that. BUT, to didactic purposes I'll be willing to tell you if you want, I don't wish any graphic interface at all. Now, a system engineer told me that what I'm gonna do is realizable and to go to Google to look for video tutorials, articles etc.... I wrote off and I hope to have made myself clear. In a few words I can't help wondering WHY in all the dozens and dozens of tutorials -that by the way are more or less copied out despite the Copyright laws- what is badly explained is how to get my target by using XAMPP, Windows, MySQL AND NOT MariaDB and php scripts that I tested but don't work - if you want I can email you them. I do believe you could create an extremely original tutorial by explaining what I wrote / pointed out. I thank you very much for your patience and I do hope to hear from you at your earliest convenience. With kind regards, Robert
December 19 2017
wtf! What a waste of perfectly good letters Joking, right?
October 10 2018
You are so great, the problem I have been facing for long has been resolved thanks to your guide... May God bless you!
November 05 2018
I'm sorry.. but I've been following your suggestion but still cannot make it.
November 06 2018
Hello, Aini. I'm sad to hear that you're having trouble :( Where exactly do you get stuck? Do you get any specific error messages while inserting data? Checking the error log could give you some good hints. Let me know how it goes ;)
March 18 2019
Thanks for tutorial, can you also create a tutorial on how to query data or view data
April 13 2019
I tried using the PDO example but it fails. I used a clean new .php file and table. I used a copy and paste with no modifications other than closing the at the end. Browser error: Parse error: syntax error, unexpected ':' in /var/www/html/hostinger.php on line 28 Line code: $my_Insert_Statement->bindParam(:first_name, $first_Name); Thanks.
April 13 2019
I'm developing this on my local machine, however I do have a paid account at Hostinger. My previous post was filtered at the end, it should say the only modification I made was closing the php section. The internet says the error likely corresponds to a missing or extra parenthesis. I'm not sure where that would be though.
April 17 2020
you have solved my problem.Thank you sir .you are too good,god bless you.
September 20 2020
Hi. I've recently tried to make an e-commerce website which is connected to the database. However, I cannot seem to insert form data into the database and can see no discernable error. I've looked closely at the code countless times and attempted to proofread against advice such as what you have offered, but still cannot identify an error. Can you please help me?
November 18 2020
Hey Kaelo. I can't see the error via the comment section, but I will ask you to message our support team and they will guide you through.
September 23 2020
Thanks. Have any examples with a long form that would make the database table have at least 200 columns? I too think that only a picky person cares about having more than one table.
November 18 2020
Hey there. Glad you find the guide useful. No examples with big tables as of now, but maybe we will update the guide with some, sometime in the future.
October 05 2020
Very Helpful ! Ignore Negative Reviews its Very Helpful, Thank You Hostinger