如何在表单字段中访问PHP变量

时间:2013-03-22 21:34:54

标签: php

这是php代码。我试图将php变量回显到表单字段textbox属性。

<?php
while($result=mysql_fetch_array($query))
{

        $title=$result["title"];
        $date=$result["date"];
        $body=$result["body"];
        $email=$result["email"];
        $id=$result["id"];
//can i use the $id variable into the form field like bellow 
//if not then how so    


echo"<form action="" method="post">";
//Here i m using  $id variable  
echo "<input type="test" name="test" value='<?php echo "$id"?>'/>";
echo "<input type="submit" name="submit" value="submit"/>";
echo "</form>";
}
?>

谢谢

4 个答案:

答案 0 :(得分:1)

你已经在php中使用了额外的php标签:只需将其作为常规var

连接
echo "<form action=\"\" method=\"post\">";
echo "<input type=\"test\" name=\"test\" value='" . $id . "'/>";//Here i m using $id       variable    
echo "<input type=\"submit\" name=\"submit\" value=\"submit\"/>";
echo "</form>";

答案 1 :(得分:1)

除非我误解了您的问题,否则您应该删除代码中的代码。

将第11行更改为:

echo '<input type="test" name="test" value="' . htmlentities($id) . '"/>';

如果id来自用户输入,则需要使用htmlentities()进行清理,否则您将打开自己的网站以访问xss(跨站点脚本)漏洞

答案 2 :(得分:0)

您无需将变量放在“”

echo "<input type='test' name='test' value='{$id?}>'/>";

这应该有效

并注意在双边引用中使用双引号而不转义它们

答案 3 :(得分:0)

你如何使用echo函数,你必须在内部排除echo并scape双引号:

echo "<form action=\"\" method=\"post\">";
echo "<input type=\"test\" name=\"test\" value=\"{$id}\" />";//Here i m using $id  variable    
echo "<input type=\"submit\" name=\"submit\" value=\"submit\"/>";
echo "</form>";

Anoter形式,更清楚的是关闭php标签并在html代码后打开它:

?> 
<form action="" method="post">
    <input type="test" name="test" value="<?php echo $id ?>" />
    <input type="submit" name="submit" value="submit" />
</form>
<?php