我正在为课堂写第一个php页面.页面应该从表单中获取输入并输出.起初我尝试使用下面的$ content变量来存储一个html块,它可以输出表单或输出.我把它放在id ="content"div中,取决于是否设置了表单元素.无论如何,我离开了这个,因为我无法正确使用_SERVER ['PHP_SELF'] varialbe.我现在放弃这个,但现在遇到了类似的问题.这是我的代码到目前为止:
<?php
if (!empty($_POST['first-name']) && !empty($_POST['last-name'])
&& !empty($_POST['age']))
{
$fname = $_POST['first-name'];
$lname = $_POST['last-name'];
$age = $_POST['age'];
$content = '<h1>About You</h1>
<h4>First Name:</h4>
<p><?php echo $fname; ?></p>
<h4>Last Name:</h4>
<p><?php echo $lname; ?></p>
<h4>Age:</h4>
<p><?php echo $age; ?></p>';
}
else
{
$content = '';
}
//get the first name, last name and age from the form
?>
<html lang="en">
<head>
<title>Personal Info Results</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div class="content">
<h1>My Form</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div id="person-info">
<label>First Name:</label>
<input type="text" name="first-name"/><br/>
<label>Last Name:</label>
<input type="text" name="last-name"/><br/>
<label>Age:</label>
<input type="text" name="age"/><br/>
</div>
<div id="submit"><input type="submit" value="Submit Info"/></div>
</form>
</div>
<div id="output">
<?php echo $content; ?>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在的问题是$ content变量中的echo函数没有导致输出出现.相反,我得到空白.我是否在String赋值中错误地定义了它?
小智 5
$content = '<h1>About You</h1>
<h4>First Name:</h4>
<p><?php echo $fname; ?></p>
<h4>Last Name:</h4>
<p><?php echo $lname; ?></p>
<h4>Age:</h4>
<p><?php echo $age; ?></p>';
Run Code Online (Sandbox Code Playgroud)
应该
$content = '<h1>About You</h1>
<h4>First Name:</h4>
<p>'.$fname.'</p>
<h4>Last Name:</h4>
<p>'.$lname.'</p>
<h4>Age:</h4>
<p>'.$age.'</p>';
Run Code Online (Sandbox Code Playgroud)
ECHO不起作用,什么也不返回.您还在<?php ?>PHP代码中使用构造.在这一刻<h1>About You</h1>不是HTML,只是字符串.