tags:

views:

114

answers:

2

I have an entry Form. When the page is loaded, it must check:

if ($_SESSION[WorkMode] == 'UPDATE')

Then fill the Form with values from the database, else open a blank Form.

If I fetch the results in a different PHP file and call this .php file on load, how to fill the Form.

A: 
$formvalue = NULL;
if ($_SESSION[WorkMode] == 'UPDATE')
    $formvalue = $some_database_value;
echo '<input type="text" name="myname" value="'.$formvalue .'" />';
antpaw
But how to populate $formvalue?
RPK
with a query to the database
marcgg
@RPK The same way you populate any other variable using data from a database (and if you don't know how to do that, then I'd suggest reading an introductory SQL in PHP tutorial rather then asking HOWTO style questions)
David Dorward
@antpaw No `htmlspecialchars`? Let's not provide examples that open up XSS attacks please!
David Dorward
shouldnt be the data that is saved in the database already XSS filtered, rather then filter it everytime you call it?
antpaw
@David: I know how to handle DB. What I wanted to know was how to load the DB result-set.
RPK
@antpaw - No. Making data safe for a particular output should be done at the level of the output. Otherwise you end up with a mess when you want to (for example) generate a PDF from the data instead of an HTML document.
David Dorward
+2  A: 

Set the variables that hold the values for your form, then include the "template" of the form you're having.

File 1:

<?php
$res = mysql_query("..");
if($res) {
  $row = mysql_fetch_assoc($res);
  $name = $row['name'];
  $birthday = $row['birthday'];
  ...
  include('form.tpl');
}

File 2 (form.tpl)

<form action="">
  <input type="text" name="username" value="<?php isset($name)?$name:""; ?>" />
  .. and so on
</form>

Alternatetively you can use a full blown template engine like Smarty to do the job for you.

Best wishes,
Fabian

halfdan
Some potential problems with this:1. If the MySQL query fails, you won't get a form being shown at all. This may be a problem for you depending on whether a failed query is acceptable behaviour.2. Depending on what data you are pre-filling, you may want to consider running it through `htmlspecialchars` or something similar before displaying it. Depends entirely on what you are displaying and how it was stored (was it sanitised before going into the DB?).
Blair McMillan
This is why I call it an "example". Security, encoding, conversion was not really a part of his question, but thanks for adding that.
halfdan