I have found this little bit of code vary useful and I thought I would give it to you all.
The basic idea here is that as an individual types something in an text field the java script runs another php file with every keystroke and yields a result in a
Its not as complicated as one might think.
This example will show you how to search an array of fruit but you can use this to display anything you want and run any php code you want. I often times use this to do LDAP and MySQL queries on the fly.
This is the javascript for the keypress feature. This needs to be on the same page as the your typing into, I generally add it in the section of my pages as a
[/php]
This is the actual code for the field and display area. field you want to use. Notice there is no submit button, that is because every thing happens when you type not when you hit submit so it is not needed.
[php]<form method=“get” action="<?php $_SERVER["PHP_SELF"] ?>">
[/php] The issue with this code is if someone hits return to submit the form you end up right back at a blank page. So.. a little e if then statement and problem resolved.
[php]<?php
if (!$_REQUEST){ // if there is nothing in the parameter fields on the URL do this.
?>
"> Search:<?php } else { // if there is something in the parameter fields do this. ?> "> Search:
" /> <?php } ?>[/php]
Now on our second file we actually preform the search of our array.
[php]<?php
$fruit = array(“apple”,“orange”,“grape”,“tomato”,“cherry”,“watermelon”); // this is our array
foreach ($fruit as $key => $value) { // this does just what it says it does… for every value in the array take the key and out put the value as a variable $value
$pos = strpos($value, $_REQUEST[‘search’]); // This searches every value in the array for a series of letters that matches what you typed
if ($pos === false) { // if no results exists do nothing
} else {
echo $value."
";
}
}
?>[/php]
and there you have it an array searched on the fly by the letters in the individual words in the array.
Here are the two files completed.
index.php:
[php]
<?php } else { // if there is something in the parameter fields do this. ?> "> Search:
" /> <?php } ?>[/php]
search.php:
[php]<?php
$fruit = array(“apple”,“orange”,“grape”,“tomato”,“cherry”,“watermelon”);
foreach ($fruit as $key => $value) {
$pos = strpos($value, $_REQUEST[‘search’]);
if ($pos === false) {
} else {
echo $value."
";
}
}
?>[/php]