You can write data into a database using the SQL INSERT command and create web pages that include PHP code to execute SQL queries on your server. Before rolling up your sleeves and coding webpages, it’s a good idea to build and test the SQL query first. In this article, we’ll show you how to insert data in phpMyAdmin using PHP.
Build the SQL command
- Log in to the HostPapa Dashboard.
- Click My cPanel in the navigation bar at the top of the page.
- Scroll down to the Databases section and select phpMyAdmin.
4. In the left sidebar, click the database name.
5. Click the database table you wish to work with. We’ll use a WordPress comments database table in this example, but you can use any database table as required.
6. In the command bar, click Insert.
7. Complete the fields, click Go to save the record.
8. The associated SQL command will display on the screen. Copy the command to a text file on your computer.
Create the PHP code
Now that the SQL command is defined, you can create the PHP code that will be used to execute the command on the server. In this example, we want a message to display on the screen thanking a user for leaving a comment on our website.
In the appropriate section of your code, you would define variables for data captured from your user – for example, their name, email address, and comment.
$the_name = $_POST['name']; $the_email = $_POST['email']; $the_website = $_POST['website']; $the_comment = $_POST['comment'];
You can use the new SQL command to submit the comment, swapping the data you entered in phpMyAdmin for the variables defined in your comment form. In the example below, we’ve selected some of the fields from the SQL query to illustrate the point.
$query = " INSERT INTO `mydatabasename` `mydatabasetable` (`comment_ID`, `comment_author`, `comment_author_email`, `comment_author_url`, `comment_content`) VALUES ('NULL', '$the_name', '$the_email', '$the_website', '$the_comment'); "; mysql_query($query); echo " Thanks for getting in touch. ";
Be sure to replace ‘mydatabasename’ and ‘mydatabasetable’ with your information. Complete the PHP code and then upload and test on your server.
If you need help with your HostPapa account, please open a support ticket from your dashboard.