2

Is it possible to add a value to a dynamically created input field?

Im trying something like this: echo "<input value="$row['test']">" but that gives me a syntax error. It has to be in my php file since im calling it via ajax and want to keep my html and php seperate.

Im getting content via ajax and I need to set many field names as there are records in the database.

Asperger
  • 3,064
  • 8
  • 52
  • 100

4 Answers4

5

You can do it like this:

echo '<input value="' . $row['test'] . '">';

Alternatively escape the " (not recommended if not needed, because it is hardly readable):

echo "<input value=\"" . $row['test'] . "\">";

Otherwise you’re mixing quotation marks, which is a syntax error. The . is to combine strings with variables (in this case).

KittMedia
  • 7,368
  • 13
  • 34
  • 38
4

You can also Use:

<input value="<?php echo htmlspecialchars($row['test']); ?>" >

OR

echo "<input name='test' value=".$row['test'].">";

OR

echo "<input name='fred' value='{$row['test']}'>";

Reference

Community
  • 1
  • 1
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
2

When using certain php values within a quoted string, such as the array syntax in the question, you should either escape from the quotes or encapsulate the variable in curly braces. Also, as the string was quoted with double quotes you should use single quotes around attributes and values.

echo "<input name='fred' value='{$row['test']}'>";
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1
<input type="text" name="post_title" class="form-control" value="<?php 
                            if(isset($post_title))echo $post_title;
                        ?>">

If you want to add it into the HTML

Nitin
  • 1,280
  • 1
  • 13
  • 17