Display data from MySQL database with HTML form and PHP

Posted by Shek on May 15, 2008 under PHP | Be the First to Comment | Total View: 45,961 views

Editor’s note: When you have all the data stored in the MySQL database, and you want to display just some particular data. In order to do so, a HTML form for them to input is a great idea. Here I have created an example to show you how to do this task.

I have created a database with a table named “test” with 2 fields “name” and “age”.
I have created a HTML file with a HTML form called “displayform.html”.
I have created a php file called “display.php”.

Here are the codes:

For displayform.html:

A HTML form with 1 text field and one submit button are created here. Users have to input the name into the “name” text field. When the submit button is clicked, the form will direct us to the “display.php” file:

<html>
<form method="post" name="display" action="display.php" />
Enter the name you like to display the data from MySQL:<br>
<input type="text" name="name" />
<input type="submit" name="Submit" value="display" />
</form>
</html>

For display.php:

First we have to connect to database:

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then we create a PHP variable to hold the value from the text field “name” of the HTML form which we fetch from displayform.html:

$name = $_POST['name'];

Now we create the query for selecting all the records which equal to the value from the textfield “name” of the HTML form.

$query = "select * from test where name = '$name'";

We run the query.

$result = mysql_query($query);

while the result is still matching the criteria of the query (it goes record by record):

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {

Print the record that matches the criteria of the query:

echo $line['name'];
echo $line['age'];
echo "<br>\n";
}

All together for display.php:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$name = $_POST['name'];
$query = "select * from test where name = '$name'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $line['name'];
echo $line['age'];
echo "<br>\n";
}
?>

Not what you want? Try a Search

Add A Comment

*