Simple Insert and Show Data from Database in PHP and MYSQL

0
204

INSERTING AND SHOWING DATA FROM DATABASE IN PHP & MYSQL

Good day everyone! Today I am going to teach you some basic knowledge about on how to insert data in database in PHP as well as showing the data inserted on it. This tutorial has a big help for beginners for starting up their dynamic websites.

Ok! Let’s start our tutorial.

First, create an “index.php” file then put the following codes.

  1. </p>
  2. <p style="padding-left: 60px;">&lt;html&gt;</p>
  3. <p style="padding-left: 60px;">&lt;head&gt;</p>
  4. <p style="padding-left: 60px;">&lt;title&gt;ITSourcecode&lt;/title&gt;</p>
  5. <p style="padding-left: 60px;">&lt;/head&gt;</p>
  6. <p style="padding-left: 60px;">&lt;body&gt;</p>
  7. <p style="padding-left: 60px;">&lt;h1&gt;Add Name Here:&lt;/h2&gt;</p>
  8. <p style="padding-left: 60px;">&lt;form method=”post” action=”insert.php”&gt;</p>
  9. <p style="padding-left: 60px;">&lt;input type=”text”  name=”name” /&gt;&lt;br&gt;</p>
  10. <p style="padding-left: 60px;">&lt;input type=”submit” value=”Save” /&gt;</p>
  11. <p style="padding-left: 60px;">&lt;/form&gt;</p>
  12. <p style="padding-left: 60px;">&lt;/body&gt;</p>
  13. <p style="padding-left: 60px;">&lt;/html&gt;</p>
  14. <p style="padding-left: 60px;">

Output:

Second, create a database. Name it as “mydatabase”.

Then create table, name it as “mydata”, then put the following columns:

my_id = primary keymy_name = textJust like this:

Then create a “connect.php” file then insert the following codes.

Then create an “insert.php” file, then put the following codes.

  1. </p>
  2. &lt;?php
  3.  
  4. Include ‘connect.php’;
  5.  
  6. if (isset($_POST[‘name’])) {
  7.  
  8. $name = $_POST[‘name’];
  9.  
  10. $insert_name = $mysqli-&gt;query(“INSERT INTO mydata (my_name) VALUES ($name’));
  11.  
  12. if ($insert_name) {
  13.  
  14. header(“Location: index.php”);
  15.  
  16. }
  17.  
  18. }
  19.  
  20. ?&gt;
  21. <p style="padding-left: 60px;">

Now, try to insert data.

Now, let’s show all the data inserted in the database.

On the index file, put the following codes below after the form.

  1. </p>
  2. &lt;php
  3.  
  4. $mydata = $mysqli-&gt;query(“SELECT * FROM mydata”);
  5.  
  6. While ($my_data = $mydata-&gt;fetch_assoc()) {
  7.  
  8. Echo ‘ID:. $my_data[‘my_id’] . ‘Name:. $mydata[‘my_name’].&lt;br&gt;;
  9.  
  10. }
  11.  
  12. ?&gt;
  13. <p style="padding-left: 60px;">

Output:

Then try to insert another data.

That’s all and thank you.

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here