Get MySQL database records as HTML form text field’s value

Posted by Shek on May 19, 2008 under PHP | Be the First to Comment | Total View: 11,997 views

In my past post on explaining how to set the default values of the text field. Now to use the same concept, we could get the records from the MySQL database and place it into the text field as default text. Here I have created an example to show you how to do so.

I have created a database with a table named “test” which has 1 field named “name” and has records stored in it.
I have created a PHP file called “test.php” to do the operation.

Here are the codes of the test.php:

First, we have to connect to the 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 query to select all records from the table “test”:

$query = "select * from test";

We run the query:

$result = mysql_query($query);

Now we use a while loop go through every record in the database and create text field with defualt text using each record in the MySQL database.

<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {?>
<input name="atextfield" type="text" value="<?php echo $line[name];?>" />

All together for test.php:

1
2
3
4
5
6
7
8
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query = "select * from test";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {?>
<input type="text" name="atextfield" value="<?php echo $line[name];?>" />
<?php } ?>

Not what you want? Try a Search

Add A Comment

*