简体   繁体   中英

content from database as default for text area in html form

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.

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>

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); ?>" />

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM