Jump to content

I wish to create a display page that will display results from searching the full name but always displays the entire file regardless of what is typed in


Bhekstar007
Go to solution Solved by Barand,

Recommended Posts

Below is the contents of a text file:

Name: John Doe| Email: johnd@gmail.com| Staff ID: SS1234| Gender: Male| School: FECS
Name: Jane Doe| Email: doejane@gmail.com| Staff ID: SS3454| Gender: Female| School: SFS
Name: Scott Doe| Email: does@gmail.com| Staff ID: SS9087| Gender: Male| School: FBDA
Name: Kelly Doe| Email: kellydoe@gmail.com| Staff ID: SS2093| Gender: Female| School: SFS

Below is the code for the display play

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<header>
	<nav>
	<ul>
		<li><a href="index.php">Main Page|</a></li>
		<li><a href="addEmployeeForm.php">Add Staff|</a></li>
		<li><a href="searchEmployeeForm.php">View Staff|</a></li>
		<li><a href="deleteEmployee.php">Delete Staff</a></li>
	</ul>
	</nav>
</header>
<body>
<h1>Staff Profile</h1>
<fieldset>
<legend>Employees Information</legend>
<?php
$name="";	
if(isset($_POST["name"])){
	$name=$_POST["name"];
}

$staffID="";
if(isset($_POST["sID"])){
	$staffID=$_POST["sID"];
}

$email="";		
if(isset($_POST["email"])){
	$email=$_POST["email"];
}

$gender="";	
if(isset($_POST["gender"])){
	$gender=$_POST["gender"];
}

$faculty="";	
if(isset($_POST["faculty"])){
	$faculty=$_POST["faculty"];
}

//$searchthis = $_POST['name'];
$file = "employees.txt";
$array= file($file);
for($x=0; $x<count($array); $x++){
	$record[]=explode("| ",$array[$x]);
	}
				for($x=0; $x<count($record); $x++){
				$search = true;		
					
				if($name==""){		
					$search=true;
		
				}elseif(strpos($record[$x][1],$name) !==false){
					$search=true;
				}else{
					$search=false;
				}
				
				if($email==""){
					$search=true;
				}elseif(strpos($record[$x][2],$email) !==false){
					$search=true;
				}else{
					$search=false;
				}
				
				if($staffID==""){
					$search=true;
				}elseif(strpos($record[$x][3],$staffID) !==false){
					$search=true;
				}else{
					$search=false;
				}
				
				if($gender==""){
					$search=true;
				}elseif(strpos($record[$x][4],$gender) !==false){
					$search=true;
				}else{
					$search=false;
				}
				
				if($faculty==""){
					$search=true;
				}elseif(strpos($record[$x][5],$faculty) !==false){
					$search=true;
				}else{
					$search=false;
				}
				
				if($search==true){
					echo $record[$x][0],"<br>"
						.$record[$x][1],"<br>"
						.$record[$x][2],"<br>"
						.$record[$x][3],"<br>"
						.$record[$x][4],"<br>";
				}
				}
?>
</fieldset>
</body>
</html>

Here is code for the form

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<header>
	<nav>
	<ul>
		<li><a href="index.php">Main Page|</a></li>
		<li><a href="addEmployeeForm.php">Add Staff|</a></li>
		<li><a href="searchEmployeeForm.php">View Staff|</a></li>
		<li><a href="deleteEmployee.php">Delete Staff</a></li>
	</ul>
	</nav>
</header>
<body>
<h1>Staff Information</h1>
<hr>
<form action="displayEmployeeinfo.php" method="post">
<p>Staff Name:</p>
<input type="text" id="name" name="name">
<p><input type="submit" name="confirm" value="Search"></p>
</form>
</body>
</html>

The basics are working but I want it to show a specific name that will display the info related to the searched name.

Edited by Bhekstar007
Typing error
Link to comment
Share on other sites

The second page should display the specific name and correlating information related to that name. Example if I search "John Doe" the second page should display John Does information only such as his email address, gender etc. To which this information is received from a text file. The problem right now is that all entries in the text file are being displayed whether the name exists in the text file or not.

Edited by Bhekstar007
Entering additional information
Link to comment
Share on other sites

Oh sorry my bad I think I may have worded my question wrong. The first code should be where the results are displayed and the second is the form I added it to help as a reference. Unfortunately I can't change the form to only search by faculty, the search has to be done by name. You said that the search is broken where in the code is it broken so I can try to fix it.

Link to comment
Share on other sites

all the code needed to search for data already exists. it is called a database engine. unless this is an assignment that requires you to store the data in a file, save yourself the trouble of redesigning a proverbial wheel again and just use a database.

your search form and form processing code should be on the same page, this results in the most secure code, the best user experience, and the simplest code. your search form should use method='get', this is a convention used on the www, where if someone finds a result they want, they can book-mark the url or share the url with others and be able to return to the same result. your search form should be 'sticky' and repopulate the field values with any existing data, this serves to both display the search term and allows the user to modify the search simply by modifying any of the field value(s). once the search form has been submitted, except for unchecked checkbox/radio fields, all the fields will be set, i.e. don't use isset() for every always-set field. if you are selecting from existing data values, rather than free typing values, which should use a wild-card match, you should use a select/option menu.

the code on any page should be laid out in this general order -

  1. initialization
  2. post method form processing - used when performing an action on the server, such as inserting, updating, or deleting data
  3. get method business logic - get/produce data needed to display the page. any code that knows how to query for and fetch data goes here...
  4. html document

regardless of the data source - database, api that returns json encoded data, a file, the code that knows how to query for and fetch the data belongs in section #3. the output from this code should be an array, that's either empty, if no matching data was found, or an array of rows of the matching data. simple php code in the html document will just test/loop over this array of data to produce the output.

your form processing code should trim, then validate all inputs before using them. if a required field is an empty string after being trimmed, that's an error. you should setup a message for the user telling them what was wrong with the data that they submitted, and not attempt to use the input data at all. if you want your query code to return all data when there is no search input, you will need to write logic to specifically do this.

if you are going to use a file to hold the data, you need to use file locking and have file error handling so that concurrent access to the file won't corrupt the data stored in the file. if you use a database for this, the database engine will take care of any locking needed for concurrent access.

after you explode the data you read from the file, you should trim each resulting element, i.e. don't assume that your file will always have exactly the white-space shown. array_map(), using either one of php's built-in functions or a user written call-back function is useful for operating on data stored in arrays. you could for example write a call-back function to take the result of the file() call, explode, trim, and build associative indexed arrays for each line read from the file.

the reason why it was suggested to get your code to work for one form field, which could initially be any of the fields, is you need to get your code to work at all, with just one field, before you can worry about all the code needed for the other fields.

 

Edited by mac_gyver
Link to comment
Share on other sites

35 minutes ago, mac_gyver said:

all the code needed to search for data already exists. it is called a database engine. unless this is an assignment that requires you to store the data in a file, save yourself the trouble of redesigning a proverbial wheel again and just use a database.

your search form and form processing code should be on the same page, this results in the most secure code, the best user experience, and the simplest code. your search form should use method='get', this is a convention used on the www, where if someone finds a result they want, they can book-mark the url or share the url with others and be able to return to the same result. your search form should be 'sticky' and repopulate the field values with any existing data, this serves to both display the search term and allows the user to modify the search simply by modifying any of the field value(s). once the search form has been submitted, except for unchecked checkbox/radio fields, all the fields will be set, i.e. don't use isset() for every always-set field. if you are selecting from existing data values, rather than free typing values, which should use a wild-card match, you should use a select/option menu.

the code on any page should be laid out in this general order -

  1. initialization
  2. post method form processing - used when performing an action on the server, such as inserting, updating, or deleting data
  3. get method business logic - get/produce data needed to display the page. any code that knows how to query for and fetch data goes here...
  4. html document

regardless of the data source - database, api that returns json encoded data, a file, the code that knows how to query for and fetch the data belongs in section #3. the output from this code should be an array, that's either empty, if no matching data was found, or an array of rows of the matching data. simple php code in the html document will just test/loop over this array of data to produce the output.

your form processing code should trim, then validate all inputs before using them. if a required field is an empty string after being trimmed, that's an error. you should setup a message for the user telling them what was wrong with the data that they submitted, and not attempt to use the input data at all. if you want your query code to return all data when there is no search input, you will need to write logic to specifically do this.

if you are going to use a file to hold the data, you need to use file locking and have file error handling so that concurrent access to the file won't corrupt the data stored in the file. if you use a database for this, the database engine will take care of any locking needed for concurrent access.

after you explode the data you read from the file, you should trim each resulting element, i.e. don't assume that your file will always have exactly the white-space shown. array_map(), using either one of php's built-in functions or a user written call-back function is useful for operating on data stored in arrays. you could for example write a call-back function to take the result of the file() call, explode, trim, and build associative indexed arrays for each line read from the file.

the reason why it was suggested to get your code to work for one form field, which could initially be any of the fields, is you need to get your code to work at all, with just one field, before you can worry about all the code needed for the other fields.

 

Hello yes I am required to store data in a text file. So from this I should try to use the get method instead of the post method. As I am retrieving data from the file and use the trim() function to display it in the proper format? Sorry if these are stupid questions I am new to php.

Link to comment
Share on other sites

searching thru a file or a table is irrelevant to the type of input method used.  Stay with the POST for collecting your input data from the form. 

Are you in the early phases of a class that is teaching you how to program?  That would be the only reason to be 'told' to use a text file rather than a db. 

Link to comment
Share on other sites

  • Solution

The first thing I'd do is convert the file data into something that is easily processed...

$filedata = file('test.txt', FILE_IGNORE_NEW_LINES);
    #
    #  organise text file data into a manageable structured array
    #
$data = [];
foreach ($filedata as $line) {
    $rec = [];
    $fields = explode('|', $line);
    foreach ($fields as $f) {
        list($k, $v) = explode(':', $f);
        $rec[trim($k)] = trim($v);
    }
    $data[] = $rec;
}

giving

$data = Array
(
    [0] => Array
        (
            [Name] => John Doe
            [Email] => johnd@gmail.com
            [Staff ID] => SS1234
            [Gender] => Male
            [School] => FECS
        )

    [1] => Array
        (
            [Name] => Jane Doe
            [Email] => doejane@gmail.com
            [Staff ID] => SS3454
            [Gender] => Female
            [School] => SFS
        )

    [2] => Array
        (
            [Name] => Scott Doe
            [Email] => does@gmail.com
            [Staff ID] => SS9087
            [Gender] => Male
            [School] => FBDA
        )

    [3] => Array
        (
            [Name] => Kelly Doe
            [Email] => kellydoe@gmail.com
            [Staff ID] => SS2093
            [Gender] => Female
            [School] => SFS
        )

)

Now it's simple to loop through the array to find the record you want

for each ($data as record} 

    if (record is required ) 
        output record contents
    end if

end for each

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.