I have a search input that pulls the first 10 results from my database while you type and eliminating those that don't match on the fly. I got this example from https://codeforgeek.com/2014/09/ajax-search-box-php-mysql/ which uses Twitter typeahead JavaScript library.
My problem, is that I have to define which column I want to search instead of choosing it in the process-search.php. What I need is to select a table column from a select field and then populate the search using the chosen column. I feel like I am close but so far it has not worked.
I have commented out the queries and code that I have tried using below the ones that work. Alos I have left the select box in the html.
Any help would be great thanks.
Index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="../inc/js/typeahead.min.js"></script>
<script type="text/javascript" src="search-script.js"></script>
<div id="search-topic-group" class="dhl-group">
<label for="term">Search By:</label>
<select name="term">
<option value="">-- Select a Search Term --</option>
<option value="username">Username</option>
<option value="city">City</option>
</select>
</div>
<div id="group" class="dhl-group">
<label for="keyword">Enter a Keyword:</label>
<input type="text" name="keyword" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Type your Query">
</div>
search-script.js
// JavaScript Document
var col = 'country'
$(document).ready(function(){
"use strict";
//Type Ahead Functions for the Search
$('select[name="term"]').change(function(){
col = $('select[name="term"]').val();
});
$('input.typeahead').typeahead({
name: 'keyword',
remote:'process-search.php?key=%QUERY&col=' + col,
limit : 10
});
});
process-search.php
<?php
$key=$_GET['key'];
$col = $_GET['col']
//$term = $_GET['term'];
$array = array();
$errors = array();
$db = mysqli_connect(<HOST>,<UID>,<PWD>,<DB>);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "select * from table_name where ".$col." LIKE '%{$key}%'";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$array[] = $row[$col];
}
echo json_encode($array);
?>