<?php
//helper function
function prepare_mysqli_where_helper($param_type, $conditions) {
$get_condition_values = function($key) use ($conditions) {
return $conditions[$key];
};
$keys = array_keys($param_type);
$condition_query = array();
foreach ($keys as $column_name) {
$condition_query[] = "`{$column_name}` = ?";
}
$where_condition = implode(' AND ', $condition_query);
$types = implode('', array_values($param_type));
$values = array_map($get_condition_values, $keys);
$types_and_values = array_merge([$types], $values);
return compact("where_condition", "types", "values", "types_and_values");
}
function refValues($arr) {
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
function filter_table($kota,$usia,$profesi,$jeniskelamin) {
$main_query = "SELECT tbl_polling.image AS Gambar, tbl_polling.nama AS Nama , COUNT(*) AS Jumlah FROM tbl_choice INNER JOIN tbl_polling ON tbl_choice.pilihan=tbl_polling.id";
$group_order = "GROUP BY tbl_choice.pilihan ORDER BY Jumlah DESC";
$conditions = array();
$param_type = array();
if ($kota != 'semuakota') {
$conditions["kota"] = $kota;
$param_type["kota"] = 's';
}
if ($usia != 'semuausia') {
$conditions["usia"] = $usia;
$param_type["usia"] = 's';
}
if ($jeniskelamin != 'semuajeniskelamin') {
$conditions["jk"] = $jeniskelamin;
$param_type["jk"] = 's';
}
if ($profesi != 'semuaprofesi') {
$conditions["profesi"] = $profesi;
$param_type["profesi"] = 's';
}
//call helper
$helper = prepare_mysqli_where_helper($param_type, $conditions);
//build query
$query = $main_query;
if (count($conditions) > 0) {
$query .= ' WHERE ' . $helper['where_condition'];
}
$query .= $group_order;
//mysqli statement prepare and bind params
$stmt = $mysqli->prepare($query);
call_user_func_array(array($stmt, "bind_param"), refValues($helper['types_and_values']));
//execute and return
$result = $stmt->execute();
return $result;
}
Comments