How to use SQL and PHP multiple criteria? - mysql

If my original code like this
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
if (!isset($_GET['urut'])) {
$urut = "" ;
} else {
$urut = $_GET['urut'];
}
if($urut == 0){ $urutkan = "id DESC"; };
if($urut == 1){ $urutkan = "harga ASC"; };
if($urut == 2){ $urutkan = "harga DESC"; };
if (!isset($_GET['jenis'])) {
$jenis = [] ;
} else {
$jenis = $_GET['jenis'];
}
if (!isset($_GET['kategori'])) {
$kategori = [] ;
} else {
$kategori = $_GET['kategori'];
}
if (!isset($_GET['wilayah'])) {
$wilayah = [];
} else {
$wilayah = $_GET['wilayah'];
}
$results_per_page = 10;
$sql = "SELECT * FROM item ";
$result = mysqli_query($link, $sql);
$number_of_results = mysqli_num_rows($result);
$number_of_pages = ceil($number_of_results/$results_per_page);
$first_page = ($number_of_results/$number_of_results);
$last_page = $number_of_pages;
$this_page_first_result = ($page-1)*$results_per_page;
$previous = ($page-1);
$next = ($page+1);
$sql='SELECT * FROM item LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
$result = mysqli_query($link, $sql);
What is the right syntax if i want the output like this
$sql='SELECT * FROM item WHERE jenis LIKE '$jenis' AND kategori LIKE '$kategori' AND wilayah LIKE '$wilayah' ORDER BY '$urutkan' LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
Thx for help
...............................................................................................................................................................................................................................................................................................................................

For use multiple criteria into MySQL query you have to use AND operator in query.
Below i give an sample to use criteria with LIKE clause.
SELECT * FROM item WHERE jenis LIKE '%'.$jenis.'%' AND kategori LIKE '%'.$kategori.'%' AND wilayah LIKE '%'.$wilayah.'%' ORDER BY $urutkan
LIMIT $this_page_first_result . ',' . $results_per_page

Related

Mysql - Get data from two tables

I have two tables webadstats and webstatsclick and i want to make below query from these two tables.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
COUNT(B.click) as 'clickss'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$impressions[] = $row['impressions'];
$clicksall[] = $row['clickss'];
$timestamp[] = $row['timestamp'];
}
for($i=0; $i<count($clicksall); $i++){
$str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i] ."\n";
}
}
echo $str;
But the problem is that this query is generating same values for both the variables impressions and clickss out of which value of impressions variable is correct.
1542434400||1270||1270
1542520800||1800||1800
1542607200||1745||1745
1542693600||1805||1805
1542780000||1615||1615
1542866400||1740||1740
1542952800||1740||1740
1543039200||1830||1830
1543125600||1830||1830
1543212000||1615||1615
1543298400||1880||1880
1543384800||2125||2125
1543471200||1530||1530
1543557600||1370||1370
1543644000||120||120
My both the DB structure is
webadstats db
webadstats db
webstatsclick db
webstatsclick db
Kindly help me where i am wrong.
Let's go back to the two query approach. The problem is, we've been trying to use JOIN on pubadhash but also WHERE with pubadhash, so the values get multiplied.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webadstats`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$sql3 = "SELECT
count(*) as 'clickss',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webstatsclick`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$arr[$row['timestamp']]['impressions'] = $row['impressions'];
$arr[$row['timestamp']]['timestamp'] = $row['timestamp'];
$arr[$row['timestamp']]['clickss'] = 0;
}
$result3 = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result3)>0) {
while($row = mysqli_fetch_assoc($result3)) {
$arr[$row['timestamp']]['clickss'] = $row['clickss'];
}
}
foreach($arr as $clicks){
$str .= $clicks['timestamp'] . '||' . $clicks['impressions'] . '||' . $clicks['clickss'] ."\n";
}
}
echo $str;

DataTables warning: table id=seo_editor_product - Invalid JSON response

I use Xampp with MariaDB 10.2.7
I installed a seo module then using json and it shows me the following error.
Error: Uncaught Exception: Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'rows' at line 1<br />Error No: 1064<br />SELECT FOUND_ROWS() as rows in C:\xampp\htdocs\store\system\library\db\mysqli.php:40
<?php
class ModelToolSeoPackageEditor extends Model {
public function __construct($registry) {
parent::__construct($registry);
if (version_compare(VERSION, '3', '>=')) {
$this->url_alias = 'seo_url';
} else {
$this->url_alias = 'url_alias';
}
}
/**
* Create the data output array for the DataTables rows
*
* #param array $columns Column information array
* #param array $data Data from the SQL get
* #return array Formatted data in a row based format
*/
public function data_output ( $columns, $data, $type = '')
{
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
// Is there a formatter?
if($column['db'] == 'related') {
$related = $this->db->query("SELECT pr.related_id, pd.name FROM " . DB_PREFIX . "product_related pr LEFT JOIN " . DB_PREFIX . "product_description pd ON pd.product_id = pr.related_id WHERE pr.product_id='" . $data[$i]['product_id'] . "' AND pd.language_id=" . $this->config->get('config_language_id') . " ORDER BY pd.name")->rows;
$old_related = $old_related_id = array();
foreach ($related as $rel) {
$old_related[] = $rel['name'];
$old_related_id[] = $rel['related_id'];
}
$data[$i]['related']['text'] = implode(', ', $old_related);
$data[$i]['related']['rows'] = $related;
}
if ( isset( $column['formatter'] ) ) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i], $type, $this );
}
else {
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
}
}
$out[] = $row;
}
return $out;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #return string SQL limit clause
*/
public function limit ( $request, $columns )
{
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #return string SQL order by clause
*/
public function order ( $request, $columns, $default )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['orderable'] == 'true' ) {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir;
}
}
if(!implode(', ', $orderBy)) return 'ORDER BY ' . $default;
$order = 'ORDER BY '.implode(', ', $orderBy);
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* #return string SQL where clause
*/
public function filter ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['searchable'] == 'true' ) {
$binding = '\'%'. $this->db->escape($str) .'%\'';
$globalSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
}
// Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' &&
$str != '' ) {
$binding = '\'%'. $this->db->escape($str) .'%\'';
$columnSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE ' . $where;
if($this->filter_language !== false) {
$where .= " AND ";
}
} else if($this->filter_language !== false) {
$where .= " WHERE ";
}
if($this->filter_language !== false) {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE status = '1'");
foreach ($query->rows as $result) {
if ($result['code'] == $this->config->get('config_language')) $default_lang = $result['language_id'];
}
if ($this->filter_language == $default_lang) {
$where .= " ( language_id = '" . $this->filter_language . "' OR language_id = '0' )";
} else {
$where .= " language_id = '" . $this->filter_language . "'";
}
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* #param array $request Data sent to server by DataTables
* #param array $sql_details SQL connection details - see sql_connect()
* #param string $table SQL table to query
* #param string $primaryKey Primary key of the table
* #param array $columns Column information array
* #return array Server-side processing response array
*/
public function simple ( $request, $type, $lang, $store, $columns )
{
$bindings = array();
$extra_select = '';
$extra_where = '';
$primaryKey = $type . '_id';
if (in_array($type, array('product', 'category', 'information'))) {
$select_cols = "`".implode("`, `", self::pluck_fields($columns, 'db'))."`";
$table = '`'.DB_PREFIX . $type . "_description` INNER JOIN `" . DB_PREFIX . $type . "` USING(" . $primaryKey . ")";
$this->filter_language = $lang;
$default_order = 'name';
// #perf: high impact
if (version_compare(VERSION, '3', '>=') || ($this->config->get('mlseo_multistore') && $this->config->get('mlseo_ml_mode'))) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND (language_id = '".(int) $lang."' OR language_id = 0) AND store_id = ".$store." LIMIT 1) AS seo_keyword";
} else if ($this->config->get('mlseo_multistore')) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND store_id = ".$store." LIMIT 1) AS seo_keyword";
} else if ($this->config->get('mlseo_ml_mode')) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND (language_id = '".(int) $lang."' OR language_id = 0) LIMIT 1) AS seo_keyword";
} else {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " WHERE query = CONCAT('".$type."_id=' , ".$type."_id) LIMIT 1) AS seo_keyword";
}
if($type == 'information') {
$default_order = 'title';
}
} elseif (in_array($type, array('manufacturer'))) {
$select_cols = "`".implode("`, `", self::pluck_fields($columns, 'db'))."`";
$this->filter_language = false;
$table = DB_PREFIX . $type . ' m';
$default_order = 'name';
$extra_select = ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " WHERE query = CONCAT('".$type."_id=' , m.".$type."_id) LIMIT 1) AS keyword";
} elseif (in_array($type, array('common', 'special'))) {
$select_cols = "`query`, `keyword`, `".$this->url_alias."_id`";
$primaryKey = $this->url_alias.'_id';
$table = DB_PREFIX . $this->url_alias;
$default_order = 'query';
if ($this->config->get('mlseo_ml_mode')) {
$this->filter_language = $lang;
if ($type == 'common') {
$extra_where = "AND query LIKE 'route=%'";
} elseif ($type == 'special') {
$extra_where = "AND query NOT LIKE 'route=%'
AND query NOT LIKE 'product_id=%'
AND query NOT LIKE 'category_id=%'
AND query NOT LIKE 'information_id=%'
AND query NOT LIKE 'manufacturer_id=%'";
}
} else {
$this->filter_language = false;
if ($type == 'common') {
$extra_where = "AND query LIKE 'route=%'";
} elseif ($type == 'special') {
$extra_where = "AND query NOT LIKE 'route=%'
AND query NOT LIKE 'product_id=%'
AND query NOT LIKE 'category_id=%'
AND query NOT LIKE 'information_id=%'
AND query NOT LIKE 'manufacturer_id=%'";
}
}
$type = 'url_alias';
} elseif ($type == 'absolute') {
$select_cols = "`query`, `redirect`, `url_absolute_id`";
$primaryKey = 'url_absolute_id';
$table = DB_PREFIX . 'url_absolute';
$default_order = 'query';
$type = 'url_absolute';
if ($this->config->get('mlseo_ml_mode')) {
$this->filter_language = $lang;
} else {
$this->filter_language = false;
}
} elseif ($type == 'redirect') {
$select_cols = "`query`, `redirect`, `url_redirect_id`";
$this->filter_language = false;
$primaryKey = 'url_redirect_id';
$table = DB_PREFIX . 'url_redirect';
$default_order = 'query';
$type = 'url_redirect';
} elseif ($type == '404') {
$select_cols = "u.`query`, u.`count`, u.`url_404_id`, (r.query IS NOT NULL) AS has_redirect";
$this->filter_language = false;
$primaryKey = 'url_404_id';
$table = DB_PREFIX . "url_404 u LEFT JOIN " . DB_PREFIX . "url_redirect r ON (u.query = r.query OR REPLACE(u.query, '".HTTP_CATALOG."', '/') = r.query)";
$default_order = 'query';
$type = 'url_404';
} else {
$this->filter_language = false;
$table = DB_PREFIX . $type;
}
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns, $default_order );
if ($type == 'url_404') {
$where = self::filter( $request, array(array('db' => 'u`.`query', 'dt' => 0)), $bindings );
} else {
$where = self::filter( $request, $columns, $bindings );
}
if (!$where) {
$where = 'WHERE 1';
}
// Main query to actually get the data
$data = $this->db->query("SELECT SQL_CALC_FOUND_ROWS ". $select_cols . "
" . $extra_select ."
FROM " . $table . ' '
. $where . ' '
. $extra_where . ' '
. $order . ' '
. $limit)->rows;
// Data set length after filtering
$resFilterLength = $this->db->query(
"SELECT FOUND_ROWS() as rows"
)->row;
$recordsFiltered = $resFilterLength['rows'];
// Total data set length
$resTotalLength = $this->db->query(
"SELECT COUNT(`{$primaryKey}`) AS total
FROM $table"
)->row;
$recordsTotal = $resTotalLength['total'];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data, $type )
);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* #param string $msg Message to send to the client
*/
public function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* #param array &$a Array of bindings
* #param * $val Value to bind
* #param int $type PDO field type
* #return string Bound key to be used in the SQL where this parameter
* would be used.
*/
public function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* #param array $a Array to get data from
* #param string $prop Property to read
* #return array Array of property values
*/
public function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
public function pluck_fields ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
if($a[$i][$prop] != 'keyword' && $a[$i][$prop] != 'related')
$out[] = $a[$i][$prop];
}
return $out;
}
}

Database Query - Order by two values (Nested Order)

I want to order results by two database values: rating_full followed by rating_count
Currently, Im ordering by the highest rating_full. it works fine.
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
…
…
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
……
The first line of code, part of the SELECT statement, retrieves the rating_full part
The second line of code is the ORDER BY part, which currently just uses the rating_count
As far as I can tell rating.meta_value referred to in the second line of code is the rating_full value
I'm trying to get it to ORDER BY rating_full, rating_count
I'm not sure how to modify the first line so that I can achieve this.
Thanks
FULL CODE:
<?php
// Sorting
add_filter('posts_join', 'directorySortingJoin',10,2);
function directorySortingJoin($join, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if ($orderby == 'rating') {
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
//$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON (wp_posts.ID = rating.post_id AND rating.meta_key IN ('rating_full')) LEFT JOIN {$wpdb->postmeta} count ON ({$wpdb->posts} = count.post_id AND count.meta_key IN ('rating_count'))";
}
if ($orderby == 'packages') {
directorySaveUserPackagesToDb();
$sql .= " LEFT JOIN {$wpdb->usermeta} packages ON ({$wpdb->posts}.post_author = packages.user_id AND packages.meta_key IN ('dir_package'))";
}
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql .= " LEFT JOIN {$wpdb->postmeta} featured ON ({$wpdb->posts}.ID = featured.post_id AND featured.meta_key IN ('dir_featured'))";
}
$join .= $sql;
//echo $join;
}
return $join;
}
add_filter('posts_orderby', 'directorySortingOrderby',10,2);
function directorySortingOrderby($orderby, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
$order = (isset($aThemeOptions->directory->defaultOrder)) ? $aThemeOptions->directory->defaultOrder : 'DESC';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if (!empty($_GET['order'])) {
$order = $_GET['order'];
}
if ($orderby == 'rating') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, convert(rating.meta_value, decimal) {$order}";
} else {
//$sql = "convert(rating.meta_value, decimal) {$order}";
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
//$sql = "cast(rating.meta_value as decimal(10,2)) {$order}, count.meta_value {$order}";
}
} else if ($orderby == 'packages') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, packages.meta_value {$order}";
} else {
$sql = "packages.meta_value {$order}";
}
} else {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, {$wpdb->posts}.{$orderby} {$order}";
}
}
$orderby = $sql;
//echo $orderby;
}
return $orderby;
}
// Save directory packages for sorting
function directorySaveUserPackagesToDb() {
$users = get_users();
// capabilities list
$roles = array(
'administrator' => 10,
'directory_5' => 9,
'directory_4' => 8,
'directory_3' => 7,
'directory_2' => 6,
'directory_1' => 5,
'editor' => 4,
'author' => 3,
'contributor' => 2,
'subscriber' => 1
);
foreach ($users as $user) {
if (isset($user->roles[0])) {
if (array_key_exists($user->roles[0], $roles)) {
update_user_meta($user->ID, 'dir_package', $roles[$user->roles[0]]);
} else {
update_user_meta($user->ID, 'dir_package', 0);
}
}
}
}
The MySQL documentation for ORDER BY should be helpful here, particularly the last paragraph on sorting multiple columns.
Your ORDER BY should be something like
ORDER BY rating_full DESC, rating_count DESC

MySQL IF Condition in Where Clause

Is it possible to decide by IF Condition which Where Clause I want to choose.
Something like:
IF(DATE_FORMAT(DATE(akDate), '%a')='SAT', USE WHERECLAUSE1, USE WHERECLAUSE2)
This is the case you can still write using rather common WHERE statement such as this:
... WHERE
(
(DATE_FORMAT(DATE(akDate), '%a') = 'SAT')
AND
(WHERECLAUSE1)
)
OR
(
(DATE_FORMAT(DATE(akDate), '%a') != 'SAT')
AND
(WHERECLAUSE2)
)
where, of course, you should replace WHERECLAUSE1 and WHERECLAUSE2 with appropriate conditions.
Easy, you should read on Boolean Algebra. In your case, here we go:
A = WhereClause1
B = WhereClause2
X = Choice
You need to select lines with X && A OR lines with !X && B. So basically your expression will be: (X && A) || (!X && B). Which leads to:
(
(Choice AND WhereClause1)
OR
((NOT Choice) AND WhereClause2)
)
$query = " SELECT apt.apt_id,apt.reg_id,apt.u_id,apt.b_id,apt.apt_bathroom,apt.apt_size,apt.apt_rent,apt.apt_desc,apt.negotiable,apt.apt_status,apt.govt_program,building.b_borough,building.b_zipcode,building.b_type,building.b_intersection,building.b_intersection2,building.b_desc FROM apt LEFT JOIN building ON apt.b_id = building.b_id WHERE apt.apt_status = 1 AND ";
if ($search_size != 'empty')
{
$query .= "apt.apt_size = '".$search_size."' ";
if ($search_borough != 'empty' || $search_zipcode != 'empty' )
{
$query .= " AND ";
}
}
if ($search_borough != 'empty')
{
$query .= "building.b_borough= '".$search_borough."' ";
if ($search_zipcode != 'empty')
{
$query .= " AND ";
}
}
if ($search_zipcode != 'empty')
{
$query .= "building.b_zipcode = '".$search_zipcode."' ";
}
$query .= "ORDER BY apt.apt_id DESC LIMIT $start,$perpage ";
$query_run = mysql_query ($query);
if (!$query_run)
{
echo 'Error In the Query limit.';
}

got a select that does 10 query in doctrine (Symfony)

I got a big query that execute 11 query, I didnt know where the problem is, but found the problem was in a select a did for geo loc, anyone has an idea how to correct that?
It happens only when i use this query SfDoctrinePaginate
Investigating further $q->select("a.longitude") create as much queries..
The problem:
$q->select("a.longitude, a.latitude, (3959 * acos(cos(radians('".$lat."')) * cos(radians(latitude)) * cos(radians(longitude) - radians('".$long."')) + sin(radians('".$lat."')) * sin(radians(latitude)))) AS distance");
the complete model:
public function getListItems($orderby, $budget, $motscles, $userid, $catID, $useDistance = false)
{
$useDistance = true;
// CHANGE ORDER
if(!$orderby){
$orderby = "a.created_at DESC";
}else if($orderby == "price"){
$orderby = "a.price ASC";
}else if($orderby == "date") {
$orderby = "a.created_at DESC";
}else{
$orderby = "a.created_at DESC";
}
// Search Keywords in table
if($motscles){
$searchItem = Doctrine_Core::getTable('csw_Article');
$results = $searchItem->search($motscles);
$ids = array();
foreach ($results as $result) {
$ids[] = $result['id'];
}
if(sizeof($ids) == 0){
$ids[] = 0;
}
}
$q = Doctrine_Core::getTable('csw_Article')
->createQuery("a")
->leftJoin('a.csw_CategorieArticle ca');
$sfContext = sfContext::getInstance()->getUser();
if($useDistance){
$lat = (string)($sfContext->getAttribute('userLat')) ? $sfContext->getAttribute('userLat') : sfConfig::get("app_user_lat");
$long = (string)($sfContext->getAttribute('userLong')) ? $sfContext->getAttribute('userLong') : sfConfig::get("app_user_long");
$radius = 18;
$q->select("a.longitude, a.latitude, (3959 * acos(cos(radians('".$lat."')) * cos(radians(latitude)) * cos(radians(longitude) - radians('".$long."')) + sin(radians('".$lat."')) * sin(radians(latitude)))) AS distance");
$q->having("distance < ?", $radius);
}
if($orderby == "distance") {
$q->orderBy("distance desc");
}
$q->addOrderBy($orderby);
if($catID){
$q->where('ca.categorie_id = ?', $catID);
}
if($budget != 0){
$budget_min = $budget - ($budget * 0.20);
$budget_max = $budget + ($budget * 0.20);
$q->addwhere('a.price > ?',$budget_min)
->addwhere('a.price < ?',$budget_max);
}
if($userid){
$q->WhereIn('a.userid = ?', $userid);
}
if($motscles){
$q->whereIn('a.id', $ids);
}
$q->execute();
return $q;
}
I would change all where by whereIn like:
if($userid){
$q->andWhereIn('a.userid', $userid);
}
if($catID){
$q->andWhereIn('ca.categorie_id', $catID);
}
I think this happens because when you're using the results in the view the paginator cant fetch all records in a row, so for each item has to do the query to get all fields.
I am really not sure why but here what was the problem:
I used
select('a.latitude')
when I should have used...
select('a.*')