如何通过php正确设置html中输入标签的值? [英] How to properly set value of input tag in html via php?

查看:105
本文介绍了如何通过php正确设置html中输入标签的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先感谢您的宝贵时间.其次,我意识到这个问题有一些答案,例如:

First of all thank you for your time. Second of all, I realize there are some answers to this question like this one: How can I set the value of a textbox through PHP? but that doesn't work for me... That being said, problem is most likely that I am doing something wrong. Basically, I have a input text tag which I use to capture the data I send to my SQL database, and display data fetched from the SQL.

我的HTML文件的一部分是:

Part of my HTML file is:

<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部分是:

The part of php that I use to send to MySQL DB is:

$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));
}

php的一部分,用于从数据库中获取数据:

Part of php for fetching data from DB:

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

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

My question is: How can I set input tag value to value that MySQL query returned?

再次感谢您,如果我的问题太新手了,请对不起!

Again, thank you and sorry if my question is too newbie!

推荐答案

如果具有 textarea ,则必须转义HTML实体.您不希望您的文本输出类似 some text</textarea>< script> window.location.href ='http://viruslocation.me';</script>< textarea> .
这样您就可以逃脱:

If you have textarea, you must escape HTML entities. You don't want your text to output something like some text</textarea><script>window.location.href='http://viruslocation.me';</script><textarea>.
So you escape:

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

此后,所有字符(如< > )将更改为& lt & gt; ,因此它们将被很好地表示,但不会被视为HTML标记.

After this, all characters like < or > will be changed to &lt; and &gt;, so they will be represented fine, but will not be seen as HTML markup.

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

For the very same reason, in tags that pass values via attributes, you only need to escape quotes

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

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

here I escaped the " character because it is the one used to delimit the attribute value. If you're using single quotes, escape them instead.

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

这篇关于如何通过php正确设置html中输入标签的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆