Get the next element in an array (PHP) - php

I have two models set up for an array. Basically, what I want to achieve is to get the first next entry from the database based on the order ID I have set up.
So, I send the ID 4, I find the entry with the ID 4 which has the order ID 15. Then I want to get the first next item after it, which should have the order ID 16. I tried incrementing with +1 after the order ID, but it just doesn't work.
With my current code I get the same array twice.
function first($id_domain) {
$this->db->select ( '*' );
$this->db->from ( 'domains' );
$this->db->where ( 'id_domain', $id_domain);
$result = $this->db->get ();
return $result->result_array ();
}
function second ($result) {
$this->db->select ( '*' );
$this->db->from ( 'domains' );
$this->db->where ( 'order', $result[0]['order'] + 1 ); //code that should get me the next entry, but doesn't work...
$this->db->where ( 'parent', $result[0]['parent'] );
$result2 = $this->db->get ();
return $result2->result_array ();
}

The problem is not due to your code, but it may be due to the records in the database: either they are non-existing for that specific condition or your matching is not entirely correct.
If you are using CodeIgniter I suggest you to alter your second function to this:
function second($result) {
$whereConds = array(
'order' => intval($result[0]['order'] + 1),
'parent'=> $result[0]['parent']
);
//if you don't have firephp print/echo/var_dump as you normally would
$this->firephp->log($whereConds);
$query = $this->db->get_where('domains', $whereConds);
$this->firephp->log($this->db->last_query());
if ($query->num_rows() <= 0) {
$this->firephp->log('No results');
return array();
} else {
return $query->result_array();
}
}
This way you can track the problem accurately.
Btw, you can also use the $offset parameter in the get_where to get the next id (perhaps just with the parent condition, since you know they are ordered sequentially):
$limit=1;
$offset=intval($result[0]['order'] + 1);//adjust depending on the parent condition below: it can be just an integer such as 2
$whereConds = array(
'parent'=> $result[0]['parent']
);
$query = $this->db->get_where('domains', $whereConds, $limit, $offset);

Related

How to show total count of comments from WP_Comment_Query in the custom Comments view for multi-author WordPress?

In my WordPress v5.8.1 I have multiple authors, I am building a new comments navigation view for each author.
There are tens of comments for each authors post, but below code I am not able to get the comments count for the respective authors posts:
function user_nav_counts($views) {
global $current_user, $wp_query;
unset($views['mine']);
unset($views['approved']);
unset($views['moderated']);
unset($views['spam']);
unset($views['trash']);
$author_ID = $current_user->ID;
$types = array(
array('status' => 'approved'),
array('status' => 'moderated'),
array('status' => 'trash')
);
foreach ($types as $type) {
$query = array(
'status' => $type['status'],
'type' => 'comment',
'post_author' => $author_ID,
'post_type' => array('song', 'book'),
'count' => true,
);
$result = new WP_Comment_Query($query);
if ($type['status'] == 'approved'):
$class = ($wp_query->query_vars['comment_approved'] == 'approved') ? ' class="current"' : '';
$views['approved'] = sprintf(__('(<span class="approved-count">%d</span>)</span>', 'approved'), ('wp-admin/edit-comments.php?comment_status=approved'), $result->count);
elseif ($type['status'] == 'moderated'):
$class = ($wp_query->query_vars['comment_moderated'] == 'moderated') ? ' class="current"' : '';
$views['moderated'] = sprintf(__('(<span class="moderated-count">%d</span>)</span>', 'moderated'), ('wp-admin/edit-comments.php?comment_status=moderated'), $result->count);
elseif ($type['status'] == 'trash'):
$class = ($wp_query->query_vars['comment_trash'] == 'trash') ? ' class="current"' : '';
$views['trash'] = sprintf(__('(<span class="trash-count">%d</span>)</span>', 'trash'), ('wp-admin/edit-comments.php?comment_status=trash'), $result->count);
endif;
}
return $views;
}
if (!current_user_can('edit_others_posts')) {
add_filter('views_edit-comments', 'user_nav_counts', 10, 1);
}
With the above code, I am able to build the new nav but the count ($result->count) is always zero.
Even in the var_dump($result), the public 'found_comments' => int 0 is also zero.
How can I get the count of each authors comments count?
the count ($result->count) is always zero
WP_Comment_Query doesn't have a property named $count, and the above call would actually cause PHP to throw a notice saying "Undefined property: WP_Comment_Query::$count".
Even in the var_dump($result), the public 'found_comments' => int 0 is also zero.
That is because the no_found_rows arg defaults to true, which means SQL_CALC_FOUND_ROWS is disabled by default.
But you should not enable it if you set count to true.
How can I get the count of each authors comments count?
Just initialize WP_Comment_Query without passing any query args and then use the query() method to get the total comments count, like so:
$comment_query = new WP_Comment_Query;
$count = $comment_query->query( $query );
But if count is not set (to true), then you would want to set no_found_rows to true and number to a non-zero integer. Example:
$query = array(
// ... your args here.
'count' => false, // 1. Don't set or set to false
'no_found_rows' => false, // 2. Set to false (default is true)
'number' => 5, // 3. Set to a non-zero value
);
$comment_query = new WP_Comment_Query( $query );
// total for the current results set, e.g. on page 1
$count = count( $comment_query->comments );
// total for all pages, same as when LIMIT is not set
$total = $comment_query->found_comments;
So you would want to use the above if you want to paginate the comments, but if you simply want the total comments, then use the count arg instead.
Edit: However, you could also simply use get_comments() like so: $views['approved'] = get_comments( $query ); if you don't need to access anything else in the class instance.
Note about the status arg
approved and moderated are not valid values for the status arg (which references the comment_approved column in the comments table), and the default statuses included in WordPress core are (see get_comment_count()):
Name
status value
Description
Pending
hold or 0
Comment is awaiting moderation
Approved
approve or 1
Comment is approved
Spam
spam
Comment is marked as spam
Trash
trash
Comment is trashed
Post Trashed
post-trashed
The comment's post is trashed
PS: approve and hold are not the actual database value, but WP_Comment_Query accepts those values in place of 1 and 0 respectively.
I think in your function you can try use something like this:
$result = new WP_Comment_Query($query);
....
$views['counts'] = count($result->get_comments());
The more details is here

Getting list of buddypress users into an array based on criteria

I am using buddypress on a wordpress installation. I would like to get an array of user_ids into a variable which I can then use to manipulate, for example, list in HTML or send messages to.
I have tried using the following code. I have verified my SQL query is correct via phpmyadmin.
function my_bp_get_users_by_xprofile( $field_id, $value ) {
global $wpdb;
$user_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT `user_id`
FROM '{$wpdb->prefix}bp_xprofile_data'
WHERE `field_id` = %d
AND `value` = %s
"
, $field_id
, $value
)
);
}
Then on the page, I want to do something like this:
$user_ids = my_bp_get_users_by_xprofile( 5, '%18%' );
echo $user_ids;
I have also verified the location of my php (bp-custom) by invoking a simple function that simply echos a string.
Where am I going wrong?
I think you're missing a return in your function, so you're calling the method but not returning anything.
function my_bp_get_users_by_xprofile( $field_id, $value ) {
global $wpdb;
$user_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT `user_id`
FROM '{$wpdb->prefix}bp_xprofile_data'
WHERE `field_id` = %d
AND `value` = %s
"
, $field_id
, $value
)
);
// Return only if there are user_id's found
if (!empty($user_ids) {
return $user_ids;
}
// Return false if nothing found
return false;
}
Then in your template you'd need to also check if its not empty:
$user_ids = my_bp_get_users_by_xprofile( 5, '%18%' );
if ($user_ids) {
// You first need to see what the structure of the returned array is and what values the indexes have
echo $user_ids['value'];
}

post an array and iterate throught it in PHP codeigniter

This is the first time i create my own webservice (someone always did it for me before), so please bear with me.
I post this array :
$data = array(
'user_id' => $this->post('user_id'),
'group_id' => $this->post('group_id'),
'child_id' => $this->post('child_id'), //will be nested array
'custom' => $this->post('custom'),
'time' => $this->post('time'),
'date' => $this->post('date')
);
I tried to create a nested array with this : $this->post('child_id'), because user can post multiple child_id at once.
Then i tried to iterate through the child_id, because i need to insert them to the mysql :
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
What should i do, so i can have an array of child_id in my $data array? (nested array)
And how to iterate through it?
UPDATE :
I have updated the codes above.
I use advanced rest client for testing, and i tried to post something like this in the form content type :
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
Notice that theres two child_id (left most and right most), but only the last one (right most) is inserted.
And this is the add_trans in the model :
function add_trans($table, $data, $schedule_id) {
$query = $this->db->insert($table, array('child_id' => $data['child_id'], 'schedule_id' => $schedule_id));
return $query;
}
Thanks a lot for your time.
Even thought you set the name attribute as child[] on the markup,
You still need to call it as:
'child_id' => $this->post('child_id')
It will still return an array.
for($i = 0; $i < sizeof($data['child_id']); $i++) {
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
EDIT:
Looking upon you query string, that seems to be the culprit:
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
^ same index , same index, same index, it will overwrite and you will get only `2`
If you want to get them all into an array format, you need to set them like this
child_id[]=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id[]=2
^ it needs to be set like this
UPDATE:
And in your model, if you want each id per row, well you can also loop in this case:
function add_trans($table, $data, $schedule_id) {
foreach($data['child_id'] as $child_id) {
$query = $this->db->insert($table, array('child_id' => $child_id, 'schedule_id' => $schedule_id));
}
// return $this->db->insert_id();
return $query;
}
ofcourse that won't work, it has to be
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data['child_id'][$i], $result_id[0]['id']);
}
because you've not set $data['child_id[]'] so it doesn't exist, the key is just a string or number, it does not validate or parse anything
you don't need to give child[] in post method. just give only child, it will get complete array what are you sending from views
replace
'child_id' => $this->post('child_id[]')
with
'child_id' => $this->post('child_id')

Returning an array of user objects from a query

I am calling a MySQL query that returns an array of user IDs. I want to pass this array if IDs to get_users to create an array of users, but I can't seem to get the code right.
My code is currently....
// get all users who have done something in the last 20 mins, or just the top 30 if there are more.
$get_user_activity='SELECT user_id FROM wp_wol WHERE last_action_date >= ( NOW( ) -2200 ) ORDER BY last_action_date DESC LIMIT 0 , 30';
$user_list = mysql_query ( $get_user_activity);
$args = wp_parse_args( $args, array( 'include' => $user_list ));
$users = get_users( 'include' => $args );
Thank you in advance.
One problem you have is that $user_list is not what you expect it to be.
You treat it like it is an array with user ID's but mysql_query() returns false or a resource on success.
You need to fetch all your rows first before you can use it in wp_parse_args() / get_users().
Something like:
$success = mysql_query($get_user_activity);
$user_list = array();
while ($row = mysql_fetch_assoc($result)) {
$user_list[] = $row['user_id'];
}

cakePHP conditions added in beforeFind function has no effect on paginate

I'm trying to filter the results of a query. A user can only see companies that have the same company_group_id as his, so I tought of adding that condition in the beforeFind function of my model.
function beforeFind($queryData) {
App::uses('CakeSession', 'Model/Datasource');
$user = CakeSession::read('Auth.User');
$queryData['conditions']['Company.company_group_id'] = $user['company_group_id'];
parent::beforeFind($queryData);
}
I can see this condition appear when I pr() my $queryData
Array
(
[conditions] => Array
(
[Company.company_group_id] => 2
)
)
Unfortunately, the resulting query when I call my paginate ignores this condition
SELECT `Company`.`id`, ... WHERE 1 = 1 GROUP BY `Company`.`id` ORDER BY `Company`.`name` asc LIMIT 10
Am I doing this correctly? Or is there another way to show the correct records to the user?
You must configure the pagination behavior in your controller's action (more about this here):
//obtaining the company_group_id
$user = CakeSession::read('Auth.User');
$id = $user['company_group_id'];
//setting the pagination conditions (similar to a find())
$this->paginate = array(
'conditions' => array('Company.company_group_id' => $id),
);
$data = $this->paginate('Company');
$this->set('data', $data);

Categories