PHP Search records from file

The task:
Write a PHP script to do the following: Read the class list in a text file, Store the records in some data structure that allows the user to search the records by ID, first name, or last name. The script provides the user with three options to input either the ID, first name, or last name, and displays the records that match the input. The script performs exact match for the ID and last name. Since the first name and middle name are stored together, the script should allow partial match for the first name. The partial match starts from the beginning. For example, if the input is “Jo”, all first names start with “Jo” should be listed out. If more than one record match the input, the script lists all of them.

You can see the script in action here:

Non-Instant version.

Ajax-ed instant search version.

Here’s my quick solution(not optimized):


Non – Ajax version :
index.php

 

<?php 
// make a variable that holds a selected option
if(isset($_POST['field'])) $selectedoption = $_POST['field'];
else $selectedoption = "fname";

// searchID looks through the given $array and for each item that matches $value in the ID field it prints a table row of data, also returning a count of found items.
function searchID(Array $array, $value) 
	{   
	$count = 0;
    	foreach ($array as $subarray)
    	{  
       	 if (isset($subarray[0]) && strtolower($subarray[0]) == strtolower($value)){
       	 	 $count++;
         	 echo "<tr><td>$subarray[0]</td><td>$subarray[2]</td><td>$subarray[1]</td></tr>n";
         	 }
   		 } 
   		 return $count;
	} 

// searchFirstName looks through the given $array and for each item that matches(even partially) $value in the first name field it prints a table row of data, also returning a count of found items.
function searchFirstName(Array $array, $value) 
	{   
		$count = 0;
    	foreach ($array as $subarray)
    	{  
       	 if (isset($subarray[2]) && stristr($subarray[2],$value)){
       	 	 $count++;
         	 echo "<tr><td>$subarray[0]</td><td>$subarray[2]</td><td>$subarray[1]</td></tr>n";
         	 }
         }
         	 return $count;
	} 

// searchLastName searchID looks through the given $array and for each item that matches $value in the last name field it prints a table row of data, also returning a count of found items.
function searchLastName(Array $array, $value) 
	{   
		$count = 0;
    	foreach ($array as $subarray)
    	{ 
       	 if (isset($subarray[1]) && strtolower($subarray[1]) == strtolower($value)){
       	     $count++;
         	 echo "<tr><td>$subarray[0]</td><td>$subarray[2]</td><td>$subarray[1]</td></tr>n";
         	 } 
        }
         	 return $count;
	} 

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHP - Read file and Search for data. Assignment 2 by Maksim Surguy</title>
<link href="style.css" media="all" rel="stylesheet" title="www" type="text/css"/>
</head>

<body>
<div id="wrapper">
<h2>Maksim Surguy - Assignment 2</h2>
<div class="alert_yellow">This is a PHP script that reads the class list from a file. The script provides a user an option to find a student record from the data structure that holds the records. User has an option to search by first (partial match), last name or by ID(exact match). If multiple records are found, the script outputs all of them.</div>
 <form name="search" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
 Seach for: <input type="text" name="find" /> in 
 <Select NAME="field">
 <Option <?php if ($selectedoption =='fname') echo 'selected ' ?>VALUE="fname">First Name</option>
 <Option <?php if ($selectedoption =='lname') echo 'selected ' ?>VALUE="lname">Last Name</option>
 <Option <?php if ($selectedoption =='id') echo 'selected ' ?>VALUE="id">ID</option>
 </Select>
 <input type="hidden" name="searching" value="yes" />
 <input type="submit" name="search" value="Search" />
 </form>
<p>
  <?php
		// read the file
        $file = fopen("classlist.txt", "r");
        $filestring = "";
        while (!feof($file)) {
        	$tempstring = fgets($file);
        	$filestring .= $tempstring."<br />";
            $line_of_text .= $tempstring;
        }
        // populate $students array - line by line
        $students = explode("n", $line_of_text);
        fclose($file);

		// separate the ID, Last name and First name
		foreach ($students as $key=>$value){
			$students[$key] = explode(",", $value);
		}

		// if the user is searching, show the results
		if ($_POST["searching"] =="yes") 
 		{ 
 			$searchterm = $_POST['find'];
 			if ($searchterm == "") 
 			{ 
 		 		echo "<p>Please put a search term"; 
		 		exit; 
 			} else {

			// need to distinguish between three different options selected in the drop down menu and act upon them.
 			switch ($_POST['field']) {
    			case "fname":
       				echo "<h3>Searching by firstname ($searchterm)</h3>";
       				echo("<table border=1><col width="60" /><col width="300" /><col width="240" /><tr><th>CWID</th><th>First Name Middle Name</th><th>Last Name</th></tr>n");
       				echo "Found ".searchFirstName($students, $searchterm)." entry/ies <hr />";
       				echo "</table>";
        			break;
    			case "lname":
        			echo "<h3>Searching by last name ($searchterm)</h3>";
        			echo("<table border=1><col width="60" /><col width="300" /><col width="240" /><tr><th>CWID</th><th>First Name Middle Name</th><th>Last Name</th></tr>n");
        			echo "Found ".searchLastName($students, $searchterm)." entry/ies <hr />";
        			echo "</table>";
        			break;
   				case "id":
        			echo "<h3>Searching by ID ($searchterm)</h3>";
        			echo("<table border=1><col width="60" /><col width="300" /><col width="240" /><tr><th>CWID</th><th>First Name Middle Name</th><th>Last Name</th></tr>n");
        			echo "Found ".searchID($students, $searchterm)." entry/ies <hr />";
        			echo "</table>";
        			break;
			}
 			}

 		}
		?>

</p>

<div class="alert_blue datarecord"><strong>Data from the file</strong>:<br /><?php echo $filestring; ?></div>
<h3>CPSC431 -  Database and Applications. 9/13/2011</h3>
</div>
</body>
</html>

jQuery Version of instant search :
index.php

<?php
// make a variable that holds a selected option
if(isset($_POST['field'])) $selectedoption = $_POST['field'];
else $selectedoption = "fname";
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript'> 
$(document).ready(function(){ 
$("#search_results").slideUp(); 
    $("#search_button").click(function(e){ 
        e.preventDefault(); 
        ajax_search(); 
    }); 
    $("#search_term").keyup(function(e){ 
        e.preventDefault(); 
        ajax_search(); 
    }); 

}); 
function ajax_search(){ 
  $("#search_results").show(); 
  var search_val=$("#search_term").val(); 
  var search_type=$("#searchtype").val();
  $.post("./find.php", {search_term : search_val, field : search_type}, function(data){
   if (data.length>0){ 
     $("#search_results").html(data); 
   } 
  }) 
} 
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHP - Read file and Search for data - AJAX version. Assignment 2 by Maksim Surguy</title>
<link href="style.css" media="all" rel="stylesheet" title="www" type="text/css"/>
</head>
<body> 
<div id="wrapper">
<h2>Maksim Surguy - Assignment 2 - AJAX Version</h2>
<div class="alert_blue">This is a PHP script that reads the class list from a file. The script provides a user an option to find a student record from the data structure that holds the records. User has an option to search by first (partial match), last name or by ID(exact match). If multiple records are found, the script outputs all of them. AJAX version shows results on the fly.</div>
 <form name="search" id="searchform" method="post">
 <div> 
 Seach for: <input type="text" name="search_term" id="search_term" /> in 
 <Select NAME="field" id="searchtype">
 <Option <?php if ($selectedoption =='fname') echo 'selected ' ?>VALUE="fname">First Name</option>
 <Option <?php if ($selectedoption =='lname') echo 'selected ' ?>VALUE="lname">Last Name</option>
 <Option <?php if ($selectedoption =='id') echo 'selected ' ?>VALUE="id">ID</option>
 </Select>
 <input type="hidden" name="searching" value="yes" />
 <input type="submit" id="search_button" name="search" value="search" />
 </div> 
 </form>
<br />
<hr />
<div id="search_results"></div> 

<br />
<h3>CPSC431 -  Database and Applications. 9/13/2011</h3>
<p>The jQuery and PHP integration was inspired by : <a href="http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/">IBM OpenSource</a></p>
</div>
</body> 
</html>

find.php

<?php

function searchID(Array $array, $value) 
	{   
		$idresult = "";
    	foreach ($array as $subarray){ 
       	 if (isset($subarray[0]) && (substr($subarray[0], 0, strlen($value)) == $value) && $value!="") 
       	 { $idresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />";   }

   		 } 
   		 return $idresult;
	} 

// searchFirstName looks through the given $array and for each item that matches(even partially) 
// $value in the first name field it prints a table row of data, also returning a count of found items.
function searchFirstName(Array $array, $value) 
	{   
		$firstresult = "";
    	foreach ($array as $subarray)
    	{  
       	 if (isset($subarray[2]) && stristr($subarray[2],$value) && $value!=""){
         	 $firstresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />";   
         	 }
         }
         	 return $firstresult;
	} 

function searchLastName(Array $array, $value){   
		$lastresult = '';
    	foreach ($array as $subarray){
       	 if (isset($subarray[1]) && stristr($subarray[1],$value) && $value!="") { $lastresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />";} 
         	 } return $lastresult;
}

$file = fopen("classlist.txt", "r");
$filestring = "";
while (!feof($file)) {
	$tempstring = fgets($file);
	$filestring .= $tempstring."<br />";
	$line_of_text .= $tempstring;
}
// populate $students array - line by line
$students = explode("n", $line_of_text);
fclose($file);

// separate the ID, Last name and First name
foreach ($students as $key=>$value){
	$students[$key] = explode(",", $value);
}

$term = strip_tags(substr($_POST['search_term'],0, 100));

$string = '';
if ($term != "" && $term != " "){
switch ($_POST['field']) {
    			case "fname":
       				$string .= searchFirstName($students, $term);
        			break;
    			case "lname":
        			$string .= searchLastName($students, $term);
        			break;
   				case "id":
        			$string .= searchID($students, $term);
        			break;
			}
}
if ($string != "") echo $string;
else echo '<div class="alert_yellow">No results found</div>';

?>

You can download complete source code below:

Download Non-Ajax version

Download Ajax version

See my other PHP code tutorials here :
All posts tagged with “PHP”

Liked it? Take a second to support Maks Surguy on Patreon!
Become a patron at Patreon!

You may also like

Leave a comment