
[英]How can I search using PHP through an XML file and display the results?
[英]how can i display the search result of employee's records in my txt file through PHP?
我被要求制作一个可以搜索员工 ID 号的 php 文件。 并将其结果从 txt 文件显示在同一页面上以供其记录......就像这样......
预期输出(同一页面上的结果):
搜索员工记录
员工编号: 12347搜索
结果:姓氏:Smith 名字:Sam 位置:编码器
注意:如果未找到用户输入,预期的消息将是“您输入的 ID 号无效”。
示例源文件:emp_record.txt
12345,Villaceran,Emelie,Instructor,20000 12346,Ayala,Jelyn,Encoder,8000 12347,Smith,Samuel,Encoder,8000
但是如果没有找到用户输入,我一直在努力写一个错误注释......也不确定我的代码结构是否适合这个......我在想我是否应该使用函数来搜索记录以及阅读和保存员工数组。 如何将员工数据保存到数组中? 我不知道我是否可以插入它..... 谁能帮我这个...
这是我的php代码..
<!DOCTYPE html>
<html>
<head>
<title>Search Employee</title>
</head>
<body>
<h1>Search Employee Record</h1>
<form method = "POST">`enter code here`
<h3>Employee ID No. :
<input type = "text" name = "id_no" >
<input type = "submit" value = "Search"></h3>
<?php
if($_POST){
$idnumber = ($_POST["id_no"]);
$empfile = fopen("emp_record.txt", "r") or die ("Unable to open file");
while (!feof($empfile)){
$employee = fgets($empfile);
$emp_record = explode(",", $employee);
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
if ($emp_id == $idnumber){
echo "Lastname : $emp_lastname <br> Firstname : $emp_lastname <br> Position : $emp_position <br>";
}else{
echo "The ID number you entered is NOT VALID.";
}
}
}
?>
</form>
</body>
</html>
这也是我使用函数的代码......我知道我的代码中仍然缺少。 我不知道如何将记录数据保存在数组中...
<?php
$empfile = fopen("emp_record.txt", "r") or die ("Unable to open file");
function record(){
while (!feof($empfile)){
$employee = fgets($empfile);
$emp_record = explode(",", $employee);
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
}
//an example loop to see if what is the datas in the variables
// it only display the last line of data
for($i=0;$i<count($emp_record);$i++){
echo "$emp_id $emp_lastname $emp_firstname $emp_position ";
}
}
?>
谢谢
您需要检查是否已显示人员详细信息,如果没有,则在循环完成后显示您的消息(因此您已检查所有记录)。
您还可以使用fgetcsv()
而不是fgets()
这将阻止您也必须执行explode()
...
$found = false;
while ($emp_record = fgetcsv($empfile)){
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
if ($emp_id == $idnumber){
echo "Lastname : $emp_lastname <br> Firstname : $emp_lastname <br> Position : $emp_position <br>";
$found = true;
break; // Stop looking
}
}
if ( $found == false ) {
echo "The ID number you entered is NOT VALID.";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.