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.

1
  • 2
    Well, perhaps you should post the syntax error first. Commented Jan 1, 2016 at 9:20

4 Answers 4

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Grüsse nach Stuttgart und frohes neues Jahr.
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

1 Comment

The second one would result in invalid HTML. value=value is not correct.
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']}'>";

1 Comment

Acording to me, this is the best way.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.