Simple Insert and Show Data from Database in PHP and MYSQL

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.

[php]
<p style="padding-left: 60px;">&lt;html&gt;</p>
<p style="padding-left: 60px;">&lt;head&gt;</p>
<p style="padding-left: 60px;">&lt;title&gt;ITSourcecode&lt;/title&gt;</p>
<p style="padding-left: 60px;">&lt;/head&gt;</p>
<p style="padding-left: 60px;">&lt;body&gt;</p>
<p style="padding-left: 60px;">&lt;h1&gt;Add Name Here:&lt;/h2&gt;</p>
<p style="padding-left: 60px;">&lt;form method=”post” action=”insert.php”&gt;</p>
<p style="padding-left: 60px;">&lt;input type=”text”  name=”name” /&gt;&lt;br&gt;</p>
<p style="padding-left: 60px;">&lt;input type=”submit” value=”Save” /&gt;</p>
<p style="padding-left: 60px;">&lt;/form&gt;</p>
<p style="padding-left: 60px;">&lt;/body&gt;</p>
<p style="padding-left: 60px;">&lt;/html&gt;</p>
<p style="padding-left: 60px;">[/php]</p>

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.

[php]

&lt;?php

Include ‘connect.php’;

if (isset($_POST[‘name’])) {

$name = $_POST[‘name’];

$insert_name = $mysqli-&gt;query(“INSERT INTO mydata (my_name) VALUES (‘$name’)”);

if ($insert_name) {

header(“Location: index.php”);

}

}

?&gt;
<p style="padding-left: 60px;">[/php]</p>

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.

[php]

&lt;php

$mydata = $mysqli-&gt;query(“SELECT * FROM mydata”);

While ($my_data = $mydata-&gt;fetch_assoc()) {

Echo ‘ID: ’ . $my_data[‘my_id’] . ‘Name: ’ . $mydata[‘my_name’]. ‘&lt;br&gt;’;

}

?&gt;
<p style="padding-left: 60px;">[/php]</p>

Output:

Then try to insert another data.

That’s all and thank you.

1 thought on “Simple Insert and Show Data from Database in PHP and MYSQL”

Leave a Comment