Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ridhamdholakia/48a69a7366827657b39c1c4dc9a03280 to your computer and use it in GitHub Desktop.
Save ridhamdholakia/48a69a7366827657b39c1c4dc9a03280 to your computer and use it in GitHub Desktop.
Search Dynamically From MySQL Database With Dynamic Column Name
/************************************* Jqueey For Input On Keyup *******************************************/
$('body').on('keyup','#search-query',function(e){
var keyword = $(this).val();
var tablename = $('#table-name').val();
var allColumns = {};
$('.filter-select').each(function () {
if($(this).val() != ''){
allColumns[$(this).attr('id')] = $(this).val();
}
});
$.ajax({
url: baseUrl+'ajax_common/search_data_from_table_using_keyword/1/table_type/'+tablename+'/filter-columns/'+JSON.stringify(allColumns)+'/search-keyword/'+keyword,
success: function(response){
$('#filteredData').html('');
$('#filteredData').html(response);
}
});
});
/************************************* Functions used in Ajax Request *******************************************/
function get_columns_from_table_name($table){
global $db;
$sql = "SHOW COLUMNS FROM table_prefix".$table;
$result = $db->execute($sql);
return $result;
}
function print_selected_data_with_filter($table,$column,$where){
global $db;
$resKeys = get_primary_key_column_name($table);
$rowKeys = $db->fetch($resKeys);
$setSql = "SELECT".$column."FROM table_prefix".$table.$where.' ORDER BY '.$rowKeys['Column_name'].' DESC';
$row = $db->execute($setSql);
return $row;
}
/************************************* Ajax Request *******************************************/
if(isset($_REQUEST['search_data_from_table_using_keyword'])) {
$table = $_REQUEST['table_type'];
$keyword = $_REQUEST['search-keyword'];
$filteres = json_decode($_REQUEST['filter-columns'],true);
$where = " WHERE ";
foreach ($filteres as $key => $value) {
$where .= " AND ".$key." LIKE '%".$value."%'";
}
$column = " * ";
$column_names = get_columns_from_table_name($table);
$numItems = $db->num_rows($column_names);
if(!empty($column_names) && $keyword != ''){
$i=0;
while ($field = $db->fetch($column_names)) {
if(++$i === $numItems) {
$wheres .= $field['Field']." LIKE '%".$keyword."%'";
}else{
$wheres .= $field['Field']." LIKE '%".$keyword."%' OR ";
}
}
$where .= $wheres;
}else{
$where .= '1=1';
}
$output = print_selected_data_with_filter($table,$column,$where);
switch ($table) {
case 'case 1':
while ($row = $db->fetch($output)) {?>
<tr>
// Display All Records
</tr>
<?php }
break;
case 'case 2':
while ($row = $db->fetch($output)) {?>
<tr>
// Display All Records
</tr>
<?php }
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment