当用户访问“访客日志”页面时,他们应该能够看到提示要求他们输入姓名的提示。提交表单后,同一页面应显示完全不同的消息,欢迎用户访问该网页。当用户刷新页面时,该过程重新开始。
到目前为止,这是我尝试过的方法,它可以工作,但是我仍然不明白如何在输入后显示一条新消息。
这是我需要的代码,仅使用PHP即可获得正确的所需结果
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p2 id="example-id-name" class="centered-text "></p>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" value="<?php echo $name;?>">
<span class="error"> <?php echo $nameErr;?></span>
<br> <br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "$name";
echo "<br>";
?>
答案 0 :(得分:1)
在回显姓名的地方,可以检查是否有姓名,然后选择要显示的消息
<?php
if($name) {
echo "Hi $name!\n Welcome to our store!"
}
else {
echo "Please enter your name"
}
echo "<br>";
?>
答案 1 :(得分:0)
您可以编写内联php和函数。
代码:
WITH song_count as
SELECT extract(year from date) AS song_year, song_code, count(*) as play_count
FROM singles NATURAL JOIN plays
group by extract(year from date),song_code
select * from song_count
where
(song_year,play_count) in (select song_year,min(play_count) from song_count group by song_year)
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}
# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}
$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = $_POST["name"] ?? "";
validate_name($name, $err);
}
?>