views:

218

answers:

3

I would like to know the easiest way to extract the text from a database field and set it as the default text for a text area.

I am planning at the moment to assiign the field to a variable, and then using javascript set it as the default text, but I am unsure of how to do this last part.

+1  A: 

If you're using a server-side language, it's not necessary to have the extra javascript step. You can simply populate the value of the "value" attribute. Here's an example using PHP:

<input type="text" 
  name="phoneNumber" 
  value="<?php print($phone_number_from_database); ?>" />
danieltalsky
+2  A: 

In your PHP code, likely above your HTML:

// Database connection calls here...
$row = mysql_fetch_array();
$databaseField = $row["databaseField"];

And in your HTML:

<textarea name="databaseField" rows="5">
   <?php= $databaseField ?>
</textarea>
John Rasch
+1  A: 

don't forget to escape your database contents!

<textarea id="foo">
  <?php echo htmlspecialchars($databasefield); ?>
</textarea>

otherwise you'll get problems with content that includes html-tags like 'foo </textarea>bar baz'. the bar baz would escape your textarea! this could lead to cross site scripting security problems (if you allow user input) or at least broken html. i used to punish fellow students by opening countless new windows with javascript if they forgot to sanitize the entries in their learning-by-doing guestbook apps. windows with images no sane person evers wants to see. good times :)

htmlspecialchars turns <, >, ", &, ... into entities (&lt;, &gt;, &quot;, &amp;, ...), preventing the content to break free.

Schnalle