AJAX Live search on MySQL db

With this script you can search a MySQL db where you get search results while you type. The maximum results on screen are 5 but it’s easily edited in the script. The results are hyperlinked into a new window.
For example i took a search of weather stations from my extreme weather site.

Host this script for free:

Web hosting

Example:


index.php:

<html>
<head>
<script>
function showResult(str) {
  if (str.length==0) { 
    document.getElementById("livesearch").innerHTML="";
    document.getElementById("livesearch").style.border="0px";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("livesearch").innerHTML=this.responseText;
      //document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
  xmlhttp.open("GET","livesearch.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

livesearch.php:

<?php
$servername = "localhost";
$username = "db_username";
$password = "db_pass";
$dbname = "db_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$q=$_GET["q"];
$sql = "SELECT station_nr, station_name, station_country FROM `weather_stations` WHERE `station_name` LIKE '%".$q."%' LIMIT 0,10";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        //echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
		echo "<a href='http://weather.friendsinwar.com/viewpage.php?page_id=1&station=".$row["station_nr"]."' target='_blank'>".$row["station_name"]." (".$row["station_country"].")</a><br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>
Download: AJAX Live Search On MySQL Db
Clicks: 63, Filesize: 1.1 KB, Date: 28 Aug. 2018

Leave a Reply

Your email address will not be published. Required fields are marked *