waa1990
waa1990

Reputation: 2413

how do I fill a html form with fields from my database?

I have a database that is filled using a form, but I wanted to be able to retrieve the fields back and fill in the form so they don't have to retype when editing.

How can I do this using PHP and MySQL?

For example I select all my columns and then I have corresponding text and check boxes on my form in my HTML file after I select them from the database. How would I put them into those boxes?

Upvotes: 1

Views: 12031

Answers (3)

k to the z
k to the z

Reputation: 3185

First, connect to the database.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

Then query the database with an SQL query.

$result = mysql_query($query);

Then pull out the individual data items and echo them where you need.

while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];

}

Upvotes: 0

d-_-b
d-_-b

Reputation: 6773

You'll need to render the form with the fields filled in. For example, the "value" attribute is used to specify the initial state of the form element.

<form>
First name: <input type="text" name="firstName" value="<?php echo $firstname; ?>" /><br />
Last name: <input type="text" name="lastName" value="<?php echo $lastname; ?>" /><br />
<input type="submit" value="Submit" />
</form>

Upvotes: 3

alex
alex

Reputation: 490647

  • Select all relevant columns from database.
  • Echo them into value attribute, determine which option should be selected, what checkbox should be checked.
  • Use htmlspecialchars() for value attributes.

Upvotes: 1

Related Questions