Dynamic mysql query LIMIT not working - mysql

I'm creating the parameters to LIMIT a mysql query using PHP variables. I'm outputting the query to make sure it's right, and it is. However the results completely ignore the offset parameter. However if I manually type in the LIMIT, it works fine.
$page_rows = 5;
$max = ($pagenum - 1) * $page_rows .',' .$page_rows;
$qry = "SELECT * FROM ".$wpdb->prefix."nslikethis_votes WHERE user_id = '$uid' AND active = 1 ORDER BY time DESC LIMIT " . $max;
$rs = mysql_query($qry);
$result = array();
if($rs && $rows>0){
while($lc = mysql_fetch_object($rs, "LikedContent")){
$result[] = $lc;
}
}
return $result;
Outputting $qry gives me this whether I use $max or manually enter '5,5':
SELECT * FROM wp_nslikethis_votes WHERE user_id = '1' AND active = 1 ORDER BY time DESC LIMIT 5,5

Try doing this for check:
$page_rows = "5";
$max = ($pagenum - 1) * $page_rows .',' .$page_rows;
$qry = "SELECT * FROM ".$wpdb->prefix."nslikethis_votes WHERE user_id = '$uid' AND `active` = 1 ORDER BY `time` DESC LIMIT " . $max;
//check for variables in query like $wpdb->prefix, $uid: are they fine, and try adding tilded sign as above
Hope this works for you

Related

I have MySQL problem: ORDER BY DESC POSTS

I have one problem. I want to order by desc for posts.
case 'posts':
// page header
page_header($system['system_title'].' - '.__("Posts Directory"));
// pager config
require('includes/class-pager.php');
$params['selected_page'] = ( (int) $_GET['page'] == 0) ? 1 : $_GET['page'];
$total = $db->query("SELECT * FROM posts") or _error(SQL_ERROR);
$params['total_items'] = $total->num_rows;
$params['items_per_page'] = $system['max_results'];
$params['url'] = $system['system_url'].'/directory/'.'posts'.'/%s';
$pager = new Pager($params);
$limit_query = $pager->getLimitSql();
// get posts
$rows = array();
$get_rows = $db->query("SELECT post_id FROM posts ".$limit_query) or _error(SQL_ERROR);
while($row = $get_rows->fetch_assoc()) {
$row = $user->get_post($row['post_id']);
if($row) {
$rows[] = $row;
}
}
$smarty->assign('rows', $rows);
$smarty->assign('pager', $pager->getPager());
break;
I can try order by post_id desc? Please help my questions.
In your query statement :
$get_rows = $db->query("SELECT post_id FROM posts ".$limit_query) or _error(SQL_ERROR);
You can change to
$get_rows = $db->query("SELECT post_id FROM posts Order By post_id DESC".$limit_query) or _error(SQL_ERROR);
I am do change in query statement get row post.. Because i don't know the use for total query statement and the select statement same too. So your question about how to do Order By Desc for Posts that's what i recommended..
Simply add this "ORDER by {field_name} DESC" to your SQL query, for example:
"SELECT * FROM posts ORDER by post_id DESC"

Selecting next related row in MySQL

I have a spatial dataset in MySQL 5.7 where I have the columns: id, deviceid, latlng_point, time. latlng_point is a geospatial Point.
What I'm trying to achieve is calculating distance from points. I'm unsure on how to approach this.
SELECT
ST_DISTANCE_SPHERE(latlng_point, i want the next latlng_point here) AS distance
FROM points
WHERE deviceid = 1
ORDER BY time DESC;
In PHP I would do something like this:
<?php
$conn = new mysqli($host,$user,$pass,$db);
$query = "SELECT latlng_point FROM points WHERE deviceid = 1...";
$latlng_array = array();
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$latlng_array[] = $row;
}
}
$distance = 0;
for ($i = 0; $i < count($latlng_array) - 1; $i++) {
$pt1 = $latlng_array[$i]['latlng_point'];
$pt2 = $latlng_array[$i+1]['latlng_point'];
$distance += haversine_function($pt1,$pt2);
}
echo "Distance: {$distance}";
?>
I'm trying to achieve something similar purely in MySQL.
Try this one:
SELECT SUM(ST_DISTANCE_SPHERE(p1.latlng_point, p2.latlng_point)) AS total_distance
FROM points p1
JOIN points p2 ON p2.id = (
SELECT p.id
FROM points p
WHERE p.deviceid = p1.deviceid
AND p.time > p1.time
ORDER BY p.time ASC
LIMIT 1
)
WHERE p1.deviceid = 1
The (correlated) subquery should return the id of the next point (sorted by time).
I can't tell you if it is really efficient or if it even works at all (can't test it).
However you should have an index on (deviceid, time) - Assuming that id is the primary key.

Select query with MAX(ad_number) issue

$r = ca_mysql_query("SELECT MAX(ad_number) FROM `myTable` WHERE `user` = {$user_id} ");
$max = $r[0]['ad_number'];
echo $max;
It should print max ad_number but its not returning any value
wheares,
if i try query removing MAX(ad_number) its returnig field data from array.
$r = ca_mysql_query("SELECT * FROM `myTable` WHERE `user` = {$user_id} ");
$max = $r[0]['ad_number'];
is returning value for the given records
whats is wrong ?
Use an alias for you column:
SELECT MAX(ad_number) as max_ad_number FROM myTable WHERE user = {$user_id}
Then do this:
$max = $r[0]['max_ad_number']; echo $max;
See documentation from w3schools here
$r = ca_mysql_query("SELECT MAX(ad_number) AS AD_NUMBER FROM myTable WHERE user = {$user_id} ");
$max = $r[0]['AD_NUMBER'];
echo $max;

How to limit time in mysql for search function

I have one problem.
I make search function in php. I need limit searching only for 1 mounth ago.
ex.
I put 'android' word
In result show only titles who containing android openet in last mounth. Oldest no show.
Thank you
EDIT
$sql = '
SELECT aa_search_index.content_id, MATCH(aa_search_index.title, aa_search_index.metadata) AGAINST (?) AS score
FROM aa_search_index
LEFT JOIN aa_thread
ON (aa_thread.thread_id = aa_search_index.content_id)
WHERE MATCH(aa_search_index.title, aa_search_index.metadata) AGAINST (?)
AND content_type = ?
AND content_id != ?
';
$params = array($query, $query, 'thread', $excludedThreadId);
if (!Search_query::get('options')->showResultsGlobal)
{
$params[] = $forum['node_id'];
$sql .= 'AND aa_thread.node_id = ?
';
}
$sql .= 'LIMIT 5';
$results = $this->fetchAllKeyed($sql, 'content_id', $params);
$threadIds = array_keys($results);
select * from your_table
where column_with_text = 'android'
and datetime_column >= curdate() - interval 1 month

zend database query limit not working as desired

i have a query to read magazine from db as
$select = $db->select()
->from('tbl_magazine',array('magazine_id','magazine_name'))
->join('tbl_magazine_issue','tbl_magazine_issue.magazine_id = tbl_magazine.magazine_id',array(null))
->join('mst_publisher','mst_publisher.publisher_id = tbl_magazine.publisher_id',array(null))
->where('tbl_magazine.is_active =?',1)
->where('mst_publisher.is_active =?',1)
->where('tbl_magazine_issue.os_select =?',2)
->where('tbl_magazine_issue.publish_status = ?',1)
->where('curdate() <= DATE(tbl_magazine.validity_till)')
->group('tbl_magazine.magazine_id')
->limit($start,$per_page);
but when i print the query i see some thing like this
SELECT `tbl_magazine`.`magazine_id`, `tbl_magazine`.`magazine_name`
FROM `tbl_magazine`
INNER JOIN `tbl_magazine_issue` ON tbl_magazine_issue.magazine_id = tbl_magazine.magazine_id
INNER JOIN `mst_publisher` ON mst_publisher.publisher_id = tbl_magazine.publisher_id
WHERE (tbl_magazine.is_active =1) AND (mst_publisher.is_active =1)
AND (tbl_magazine_issue.os_select =2) AND (tbl_magazine_issue.publish_status = 1)
AND (curdate() <= DATE(tbl_magazine.validity_till))
GROUP BY `tbl_magazine`.`magazine_id`
LIMIT 2147483647 OFFSET 8
but i have set $start as 0 and $perpage as 8
i was looking for a query with limit as "limit 0 ,8"
you are not using limit correctly.
Here is function definition from Zend_Db_Select. As you can see 1st param is count and not offset.
/**
* Sets a limit count and offset to the query.
*
* #param int $count OPTIONAL The number of rows to return.
* #param int $offset OPTIONAL Start returning after this many rows.
* #return Zend_Db_Select This Zend_Db_Select object.
*/
public function limit($count = null, $offset = null)
{
$this->_parts[self::LIMIT_COUNT] = (int) $count;
$this->_parts[self::LIMIT_OFFSET] = (int) $offset;
return $this;
}
And just to explain why you were getting those crazy values... Below is part of script that renders the SQL query. Because you had offset it was setting count to PHP_INT_MAX.
if (!empty($this->_parts[self::LIMIT_OFFSET])) {
$offset = (int) $this->_parts[self::LIMIT_OFFSET];
$count = PHP_INT_MAX;
}