Alphabetic Search First Letter A to Z Script Tutorial PHP MySQL
Learn to program alphabetic A-Z first letter search scripts using PHP, JavaScript, HTML and CSS. The buttons or links HTML code can be rendered dynamically in a loop to save some byte space and are easier to change or edit later. Through this loop we establish JavaScript click event handling and send dynamic data to the search results page. The buttons can appear anywhere you like on your website.
example.html
<!DOCTYPE html>
<html>
<head>
<script>
var btns = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var letterArray = letters.split("");
for(var i = 0; i < 26; i++){
var letter = letterArray.shift();
btns += '<button class="mybtns" onclick="alphabetSearch(\''+letter+'\');">'+letter+'</button>';
}
function alphabetSearch(let){
window.location = "search_results.php?letter="+let;
}
</script>
</head>
<body>
<script> document.write(btns); </script>
</body>
</html>
search_results.php
<?php
$results = "";
$letter = "";
if(isset($_GET['letter']) && strlen($_GET['letter']) == 1){
$letter = preg_replace('#[^a-z]#i', '', $_GET['letter']);
if(strlen($letter) != 1){
echo "ERROR: Hack Attempt, after filtration the variable is empty.";
exit();
}
// Connect to database here now
// SELECT * FROM movies WHERE title LIKE '%$letter'
// Use a while loop to append database results into the $results variable ($results .=)
// Close your database connection here after your while loop closes
// The line below is only to use for testing purposes before you
// attempt to connect to your database and query it, remove this line after initial test
$results = "PHP recognizes the dynamic ".$letter." and can search MySQL using it";
}
?>
<html>
<body>
<?php echo $results; ?>
</body>
</html>