我正在开发一个项目,我的脚本需要允许工作人员在表单中输入表演者/乐队名称,并在提交表单时看到正确的相应电话号码。
我得到的文本文件如下:
Spiders 0392848271
TheBESTband 0482947291
Lauren 0382718319
Queen 0482827183
KateIsland 0373829420
Reposessed 0472478292
HighRollers 0289428372
Mindstorm 0347287492
WhirlyBirds 0272729193
Traceylyly 0303828294
我已经编写了代码来解析文本文件并将值存储到关联数组中,但我需要知道如何从表单获取输入并将其与关联数组匹配并打印相应的电话号码。
<!DOCTYPE html>
<html>
<body>
<?php
$filename = "performers.txt";
$myfile = fopen($filename, "r") or die("Unable to open file!");
$content = array();
while(!feof($myfile)) {
$content[] = fgets($myfile);
}
fclose($myfile);
$data = array();
foreach($content as $line) {
$pieces = explode(' ', $line);
$data[trim($pieces[0])] = trim($pieces[1]);
}
foreach ($data as $name => $phoneno) {
if (isset($_POST['performer']))
{
$performer=$_POST['performer'];
foreach ($data as $name => $phoneno)
{
if ($name == $performer)
{
echo $phoneno;
}
}
}
}
?>
</body>
<html>
我的html编码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Melbourne Performance Hall </title>
<style>
body {
font-family: Arial;
width: 1200px;
margin: auto;
}
h1 {
background-color: #AACCFF;
text-align: center;
}
form {
width: 1000px;
margin: auto;
background-color: #AA77FF;
padding: 2px;
color: #FFF;
}
label {
font-weight: bold;
color: #FFF;
}
span {
display:inline-block;
width: 100px;
}
p {
font-size: 20px;
}
</style>
</head>
<body>
<h1>Melbourne Performance Hall <br> Performer Phonebook </h1>
<p> Enter the performer or band name with no spaces <br> If found, the phone number will be displayed.</p>
<form action="findPerformerD.php" method="get">
<fieldset>
<p align="left">
<label> Performer/ band name: </label>
<input type="text" name="performer" size="50"> <br>
<input type="submit" name="submit" value="Submit performer name"> </p>
</fieldset>
</form>
</body>
</html>
这就是我所做的,但是当我尝试 html 表单时,它所做的只是给我一个白色页面。
首先,您的表单通过 GET 而非 POST 提交,因此
$_POST
中不会填充任何内容。
你可以改变
<form action="findPerformerD.php" method="get">
到
<form action="findPerformerD.php" method="post">
解决这个问题。
其次,您无缘无故地循环访问
$data
数组两次。这不能帮助您找到匹配的数据。
事实上,尽管你根本没有循环来进行测试: 。相反,您可以尝试直接访问表演者记录 - 这就是使用以表演者姓名作为索引的关联数组的有用之处。
在 PHP 中,将整个
foreach ($data as $name => $phoneno) { ... }
部分替换为:
if (isset($_POST['performer']))
{
if (isset($data[$_POST['performer']])
{
echo "Phone number is: ".$data[$_POST['performer']];
}
else
{
echo "No matching performer found";
}
}
因此,例如,如果您要在表单中输入
Lauren
,您会期望它输出“电话号码是:0382718319”