pagination not showing on custom query (get_results) - wordpress-theming

I followed this link and created my own custom query with pagination.. but I don't really understand how the offset works,
https://wordpress.stackexchange.com/questions/21626/pagination-with-custom-sql-query
the pagination does not work well. and I'm getting zero value for offset.
function spiciest(){
global $wpdb, $paged, $max_num_pages;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_per_page = intval(get_query_var('posts_per_page')); //6
$offset = ($paged - 1)*$post_per_page;
/* Custom sql here. I left out the important bits and deleted the body
as it will be specific when you have your own. */
$sql = "
SELECT DISTINCT * FROM $wpdb->posts
INNER JOIN (SELECT *, SUBSTRING(name, 6) as 'post_ID',
votes_up AS votes_balance,
votes_up + votes_down AS votes_total
FROM thumbsup_items) AS thumbsup
ON $wpdb->posts.ID = thumbsup.post_ID
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_password = ''
ORDER BY votes_up DESC, votes_balance DESC
LIMIT ".$offset.", ".$post_per_page."; ";
$sql_result = $wpdb->get_results( $sql, OBJECT);
/* Determine the total of results found to calculate the max_num_pages
for next_posts_link navigation */
$sql_posts_total = $wpdb->get_var( "SELECT FOUND_ROWS();" );
$max_num_pages = ceil($sql_posts_total / $post_per_page);
print_r("offset ". $offset."\n") ;
print_r("\n"."sql_posts_total ". $sql_posts_total."\n") ;
print_r("\n"."max_num_pages ". $max_num_pages."\n") ;
return $sql_result;
}
Please see it live.. I have printed the vlues.. http://goo.gl/fZTck
It should have 7 pages with a total of 39 entries.

The problem here is the LIMIT, it'll just count the first page and not the entire query.
I had solved it by providing a secondary SQL query for counting the max pages. thanks for my friends for this tip.
here's the complete code.
function.php
function spiciest(){
global $wpdb, $paged, $max_num_pages;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_per_page = intval(get_query_var('posts_per_page')); //6
$offset = ($paged - 1)*$post_per_page;
// query normal post
$query_spicy = "
SELECT DISTINCT * FROM $wpdb->posts
INNER JOIN (SELECT *, SUBSTRING(name, 6) as 'post_ID',
votes_up AS votes_balance,
votes_up + votes_down AS votes_total
FROM thumbsup_items) AS thumbsup
ON $wpdb->posts.ID = thumbsup.post_ID
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_password = ''
ORDER BY votes_up DESC, votes_balance DESC";
//query the posts with pagination
$spicy = $query_spicy . " LIMIT ".$offset.", ".$post_per_page."; ";
$spicy_results = $wpdb->get_results( $spicy, OBJECT);
// run query to count the result later
$total_result = $wpdb->get_results( $query_spicy, OBJECT);
$total_spicy_post = count($total_result);
$max_num_pages = ceil($total_spicy_post / $post_per_page);
return $spicy_results;
}
TEMPLATE CODES:
<?php
$spiciest = spiciest();
if ($spiciest):
global $post;
foreach ($spiciest as $post) :
setup_postdata($post);
?>
/**** PUT TEMPLATE TAGS HERE *****/
<?php
endforeach;
endif;
?>
and then the PAGINATION here, please note of the TOTAL in array.
global $wp_rewrite, $wp_query, $max_page, $page;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => #add_query_arg('page','%#%'),
'format' => '',
'total' => $max_num_pages,
'current' => $current,
'prev_text' => __('PREV'),
'next_text' => __('NEXT'),
'end_size' => 1,
'mid_size' => 2,
'show_all' => false,
'type' => 'list'
);
if ( $wp_rewrite->using_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );
if ( !empty( $wp_query->query_vars['s'] ) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );
echo paginate_links( $pagination );

Your variable $offset value is always the same.
So just replace
$offset = 1;
with:
$offset = ($paged - 1)*$post_per_page;

Related

How to transform raw SQL into Yii2 like find query

I can't convert raw SQL query in to Yii2 like method. I'd like to implement grid view from my RAW sql with filtering and sorting. I'm using ActiveDataProvider with method in the ModelSearch as Yii default way.
I did try to use Model::findBySql but it is not letting me filter or sort my results in the grid view. I don't want to useSQLDataProvider because I have relations in my queries.
I see that changing Model::FindBySql($sql) to Model::find is letting me sort and filter but the results are not as expected. I have to transform this SQL to use Model::Find() method
My sql I struggle to change is
$sql = 'SELECT A.*, (6371 * acos(cos(radians("'.$mapSearch->gps_lat.'")) * cos(radians(gps_lat))*cos(radians(gps_long)-radians("'.$mapSearch->gps_long.'"))+sin(radians("'.$mapSearch->gps_lat.'"))*sin(radians(gps_lat)))) AS distance FROM address A JOIN contest_has_address CA On A.id = CA.address_id JOIN contest C On C.id = CA.contest_id JOIN contest_has_date CD On C.id = CD.contest_id JOIN date D On D.id = CD.date_id WHERE main = 1 AND C.status = 1 AND D.start_time > "'.$today.'" HAVING distance < "'.$mapSearch->distance.'" ORDER BY distance ASC';
my Controller:
if($mapSearch->save(false)) {
$lat = $mapSearch->gps_lat;
$long = $mapSearch->gps_long;
$sql = 'SELECT A.*, (6371 * acos(cos(radians("'.$mapSearch->gps_lat.'")) * cos(radians(gps_lat))*cos(radians(gps_long)- radians("'.$mapSearch->gps_long.'"))+sin(radians("'.$mapSearch->gps_lat.'") )*sin(radians(gps_lat)))) AS distance FROM address A JOIN contest_has_address CA On A.id = CA.address_id JOIN contest C On C.id = CA.contest_id JOIN contest_has_date CD On C.id = CD.contest_id JOIN date D On D.id = CD.date_id WHERE main = 1 AND C.status = 1 AND D.start_time > "'.$today.'" HAVING distance < "'.$mapSearch->distance.'" ORDER BY distance ASC';
$models = Address::findBySql($sql)->all();
$count = Yii::$app->db->createCommand($sql)->queryScalar();
$dataProvider = $searchModel->searchMapAddress(Yii::$app->request->queryParams, $sql);
return $this->render('map', [
'sql'=>$sql,
'searchModel'=>$searchModel,
'models'=>$models,
'dataProvider'=>$dataProvider,
'mapSearch'=>$mapSearch,
'lat'=>$mapSearch->gps_lat,
'long'=>$mapSearch->gps_long,
]);
My Model
$query = Address::findBySql($sql);
$query->joinWith(['contest']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
and view:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=> '{items}',
Assuming that your raw SQL query is working correctly you can use ActiveRecord or Query Builder to create your query.
For using MYSQL functions inside the query you must use \yii\db\Expresion, and while building the query you should use ->createCommand()->rawSQL at the end of the query replacing with ->one() or ->all(), and echo the query to see what the RAW SQL query is built and compare it with the original query.
You can use the following query:
$query=Address::find()->alias('A')
->select([new Expression('A.*, (6371 * acos(cos(radians("' . $mapSearch->gps_lat . '")) * cos(radians(gps_lat))*cos(radians(gps_long) -radians("' . $mapSearch->gps_long . '")) + sin(radians("' . $mapSearch->gps_lat . '"))*sin(radians(gps_lat)))) AS distance')])
->join('left join', '{{content_has_address}} CA', 'A.id = CA.address_id')
->join('left join', '{{contest}} C', 'C.id = CA.contest_id')
->join('left join', '{{contest_has_date}} CD', 'C.id = CD.contest_id')
->join('left join', '{{date}} D', 'D.id = CD.date_id')
->where(
['AND',
['=', 'main', 1],
['=', 'C.status', 1],
['>', 'D.start_time', $today]
]
)
->having(['<', 'distance', $mapSearch->distance])
->orderBy('distance asc');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);

Rewrite SQL Select to use $wpdb->prepare

I'm trying to rewrite an SQL select query to use the $wpdb->prepare function. My original SQL query looks like this and works fine.
function hfwp_SaveFormData($formData, $userID, $today, $dbTable) {
global $wpdb;
$wpdb->show_errors();
$query = "SELECT UserID FROM $dbTable WHERE Date = '$today' AND UserID = '$userID'";
$wpdb->get_results( $query );
$count = $wpdb->num_rows;
if ($count > 0) {
$wpdb->update($dbTable, array('Distance' => $formData), array('Date' => $today, 'UserID' => $userID));
}else{
$wpdb->insert($dbTable, array('UserID' => $userID, 'Date' => $today, 'Distance' => $formData));
}
}
I then tried to rewrite the SELECT statement to use $wpdb->prepare:
$wpdb->get_results( $wpdb->prepare("SELECT UserID FROM %s WHERE Date = %s AND UserID = %d", $dbTable, $today, $userID ) );
But it gives an error in the log but not enough to give me a hint on what is wrong.
I also tried another version of the $wpdb->prepare:
$query = "SELECT UserID FROM %s WHERE Date = %s AND UserID = %d";
$prepared = $wpdb->prepare( $query , $dbTable, $today, $userID );
$wpdb->get_results( $prepared );

Convert raw sql to ZF2 statement

In zf2, how can i write following mysql query and execute it. ??
SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title,'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0) result ON um.module_id = result.id
WHERE um.user_id='3'
I found solution!!
$userId = '1';
$select = "SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title, 'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0)) temptable on um.module_id = temptable.id where um.user_id='". $userId ."'";
$resultSet = $this->adapter->query($select);
return $data = $this->resultSetPrototype->initialize($resultSet->execute())->toArray();
OR else can use ZF2 method:
$sql = new Sql($this->getAdapter());
$select = $sql->select()->from(array('um' => $this->table));
Get all slideshow modules
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1->where("slideshow.is_deleted = 0");
$select1->order("slideshow.id");
Get all video modules
$select2 = $sql->select(array())->from(
array("video" => 'video_master'))
->columns(
array('id','module_code','module_title',"type" => new Expression("'Video'")));
$select2->where("video.is_deleted = 0");
$select2->order("video.id");
union of two first selects
$select1->combine ( $select2, 'UNION' );
$select->join(array('result' => $select1), "result.id = um.module_id");
$select ->where("um.user_id='". $userId. "'");
$statement = $sql->prepareStatementForSqlObject($select);
return $this->resultSetPrototype->initialize($statement->execute())->toArray();
Sorry for my typing and formatting.

query with parentheses in zend framework 2.2

I want my query like this:
SELECT tbl_bids. * , tbl_department.vDeptName, tbl_user.vFirst
FROM tbl_bids
LEFT JOIN tbl_bids_department ON tbl_bids_department.iBidID = tbl_bids.iBidID
LEFT JOIN tbl_department ON tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_bids.iUserID
WHERE tbl_user.iUserID = '1' // with parantheses in where clause
AND (
tbl_department.vDeptName = 'PHP'
OR tbl_department.vDeptName = 'android'
)
GROUP BY tbl_bids.iBidID
ORDER BY iBidID DESC
LIMIT 0 , 30
But i can't find the way to get parantheses in my query,there are mutiple condition and loop will be there to make where clause..
here is my code
$select = $this->tableGateway->getSql()->select();
$select->columns(array('*'))
->join('tbl_bids_department', 'tbl_bids_department.iBidID = tbl_bids.iBidID', array(),"LEFT")
->join('tbl_department', 'tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID',array(tbl_department.vDeptName),"LEFT")
->join('tbl_user', 'tbl_user.iUserID = tbl_bids.iUserID',array(tbl_user),"LEFT")
->group('tbl_bids.iBidID');
$where = new \Zend\Db\Sql\Where();
$where->equalTo( 'tbl_bids.eDeleted', '0' );
$sWhere = new \Zend\Db\Sql\Where();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if (isset($data['sSearch_'.$i]) && $data['sSearch_'.$i] != "")
{
if($aColumns[$i] == 'vDeptName'){
$allDept = explode(',', $data['sSearch_'.$i]);
foreach ($allDept as $key => $value) {
if($key == 0)
$sWhere->AND->equalTo("tbl_department.vDeptName", $value);
else
$sWhere->OR->equalTo("tbl_department.vDeptName", $value);
}
}elseif($aColumns[$i] == 'vFirst')
$sWhere->AND->equalTo("tbl_user.iUserID",$data['sSearch_'.$i]);
else
$sWhere->AND->like("tbl_bids.".$aColumns[$i], "%" . $data['sSearch_'.$i] . "%");
$select->where($sWhere); // here my where clause is create
}
}
//var_dump($select->getSqlString());
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
I have others many fields to pass through where which also have same problem of paratheses
if there is no any condition i can use nest() and unnest() predicate , but it will show me that string is not nested error,
So pls help me to find the solution.
Pls attach example with solution.
here is a short example
$where = new Sql\Where();
$where->equalTo('col',thirdVal')
->NEST //start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet
hope this will help

A duplicate key is inserted instead of updated in a SQL INSERT / UPDATE query

I have the below function in Wordpress.
However, the meta key product_price is duplicated each time a post is updated.
Like this image
Is there any way to prevent this?
function do_my_stuff($post_ID) {
global $post,$wpdb;
$tablename="wp_cart66_products";
if($post->post_type == "post" && strlen( get_post_meta($post_ID, 'price', true))>0 )
{
$id = $wpdb->get_var("SELECT id FROM ".$tablename." WHERE id=".$post_ID);
$cny = get_post_meta($post->ID, 'price', true);
/*Shipping rate */
if( $cny < 50 )
$shipping = 14.97;
else if( $cny >= 50 && $cny < 200 )
$shipping = 22.59;
else if( $cny >= 200 && $cny < 250 )
$shipping = 24.59;
else if( $cny >= 250 && $cny < 300 )
$shipping = 26.60;
else if( $cny >= 300 )
$shipping = 29.27;
/*Exchange rate CNY to EURO */
$cny_to_euro = 0.124;
$euro = $cny * $cny_to_euro ;
$price = $euro + $shipping;
$price = number_format($price,2);
$data=array(
'id'=>$post_ID,
'item_number'=>get_post_meta($post->ID, 'scode', true),
'name'=>$post->post_title,
'price'=>$price,
'options_1'=>get_post_meta($post->ID, 'variations', true),
'shipped'=>'1',
);
$where = array("id" => $post_ID);
// Possible format values: %s as string; %d as decimal number; and %f as float.
$format=array( '%d', '%s', '%s', '%s', '%s', '%d');
$where_format = array( '%d' );
if($id>0){
// update
$wpdb->update( $tablename,$data, $where, $format, $where_format);
}else{
// insert
$wpdb->insert( $tablename,$data,$format);
}
AddMetaPrice ( $post_ID ) ;
}
return $post_ID;
}
function AddMetaPrice ( $post_ID )
{
// init
global $post,$wpdb;
// We add the wordpress post ID and price to a meta tag
$metaKey = "product_price" ;
$tableName = "wp_cart66_products" ;
$metaQuery = "SELECT price FROM $tableName WHERE id='$post_ID'" ;
$metaValue = $wpdb->get_var( $metaQuery ) ;
$tableName = "wp_postmeta" ;
// Do we have this post already?
if ( $id > 0 )
{
// this already exists. we only need to update
// $metaQuery = "UPDATE $tableName SET meta_value='$metaValue' WHERE meta_key='$metaKey' AND post_id='$id'" ; // we use wordpress's method instead
$data = array ( "meta_value" => $metaValue ) ;
$where = array ( "meta_key" => $metaKey, "post_id" => $post_ID ) ;
$wpdb->update( $tableName, $data, $where ) ;
}
else
{
// this is not created, we need to create it now (insert)
// $metaQuery = "INSERT INTO $tableName (post_id, meta_key, meta_value) VALUES ('$id', '$metaKey', '$metaValue')" ; // we use wordpress's method instead
$data = array ( "post_id" => $post_ID, "meta_key" => $metaKey, "meta_value" => $metaValue ) ;
$wpdb->insert( $tableName, $data ) ;
}
}
add_action('publish_post', 'do_my_stuff');
I've read here that a ON DUPLICATE KEY statement exists. But i'm not sure if it can be implemented in the above code.
Try replacing that piece of code:
if ( $metaValue !== NULL )
{
update_post_meta($post_ID, $metaKey, $metaValue); // use built-in function instead
}
where it was:
// Do we have this post already?
if ( $id > 0 )
{
// this already exists. we only need to update
// $metaQuery = "UPDATE $tableName SET meta_value='$metaValue' WHERE meta_key='$metaKey' AND post_id='$id'" ; // we use wordpress's method instead
$data = array ( "meta_value" => $metaValue ) ;
$where = array ( "meta_key" => $metaKey, "post_id" => $post_ID ) ;
$wpdb->update( $tableName, $data, $where ) ;
}