如何通过PHP在html中正确设置输入标签的值?

时间:2014-02-03 16:29:41

标签: php html post input

首先感谢您的时间。 其次,我意识到这个问题有一些答案就像这样:How can I set the value of a textbox through PHP? 但这对我不起作用......话虽如此,问题很可能就是我做错了什么。 基本上,我有一个输入文本标记,用于捕获我发送到SQL数据库的数据,并显示从SQL获取的数据。

我的HTML文件的一部分是:

<form name="editForm" action="./edit.php" method="POST">
    <label>Foo</label><input name="fooBar" type="text" />
    <button name="btnStudent" value="Submit" onclick="submit()">Submit</button>
</form>

我用来发送到MySQL DB的php部分是:

$conn = mysqli_connect("localhost", "user", "pwd", "fooDB");
$fooBar = $_POST["fooBar"];
if (!mysqli_query($conn, "INSERT INTO fooTable (foobar) VALUES ('$fooBar')")) {
    die("Failed: " . mysqli_error($conn));
}

从DB获取数据的部分PHP:

$result = mysqli_query($conn, "SELECT * FROM fooTable WHERE foobar='$fooBar'");
$data = mysqli_fetch_array($result);

我的问题是:如何将输入标记值设置为MySQL查询返回的值?

再次,谢谢你,如果我的问题太新手了,我很抱歉!

3 个答案:

答案 0 :(得分:1)

如果您有textarea,则必须转义HTML实体。您不希望文本输出some text</textarea><script>window.location.href='http://viruslocation.me';</script><textarea>之类的内容 所以你逃脱了:

<textarea><?php echo htmlentities($value); ?></textarea>

在此之后,<>等所有字符都将更改为&lt;&gt;,因此它们会被很好地表示,但不会被视为HTML标记。

出于同样的原因,在通过属性传递值的标记中,您只需要转义引号

<input type="text" value="<?php echo str_replace('"', '\\"', $value); ?>"/>

这里我转义了"字符,因为它是用于分隔属性值的字符。如果您使用单引号,请转义它们。

<input type="text" value="<?php echo addslashes($value); ?>"/>

答案 1 :(得分:0)

在文本框中插入值:

<input type="text" name="param" value="<?php echo your_value; ?>" />

答案 2 :(得分:0)

  • 请在文本的开头和结尾添加 '(一个引号)。
<!DOCTYPE html>
<html>
<body>

<?php
  $txt = "'PHP Laravel Javascript'";
  
  echo "<input type='text' value=$txt />"
?>

</body>
</html>

enter image description here enter image description here