Wordpress - use $wpdb->update and limit 1 - mysql

It's probably a stupid question but I'm trying to use $wpdb->update instead of $wpdb->query but I'm not sure how to use limit 1. So instead of
$wpdb->query("update {$wpdb->prefix}vp_pms_group_users set read = '1', seen = '1', time_seen = '{$date_time_seen}' where message_id = '{$last_message_id}' and group_id = '{$group_id}' and to_username = '{$session_uid}' and read = '0' limit 1");
I've tried with
$wpdb->update($wpdb->prefix . "vp_pms_group_users", array(
'read' => '1',
'seen' => '1',
'time_seen' => $date_time_seen,
),
array(
'message_id' => $last_message_id,
'group_id' => $group_id,
'to_username' => $session_uid,
'read' => '0',
),
LIMIT 1 //????
);
Should I use limit after the array or inside it?
Thanks.

Here's an answer, it's not pretty, but based on looking through the method chain within $wpdb it's possibly the only way to achieve what you're after, and still use $wpdb->update().
Step 1.
Make your update with a unique parameter which you'll later replace, note that this must be the last parameter passed to the WHERE clause, otherwise replacing it with LIMIT 1 will cause a syntax error in your SQL statement.
Something like:
$wpdb->update(
$wpdb->prefix . "vp_pms_group_users",
array(...),
array(
...
'MyReplacementLimit' => 1
)
);
This should give you an SQL statement like so:
UPDATE vp_pms_group_users SET ... WHERE ... AND MyReplacementLimit = 1;
Step 2:
Now you can use the query filter to replace that fake clause with a limit...
add_filter('query', function ($query) {
return str_replace('AND MyReplacementLimit = 1', 'LIMIT 1', $query);
});
This is untested and is based purely on reading through the code available in $wpdb. It may need a few tweaks to get working correctly.
A simpler solution:
You could always just use SQL directly, so long as you're using $wpdb->prepare() it's probably easier to read, and more understandable than the above approach.

you should change Previous answer add_filter to this:
add_filter('query', function ($query) {
return str_replace("AND `MyReplacementLimit` = '1'", 'LIMIT 1', $query);
});

Related

mysql query for category and date

How can I query the wordpress database so that I'm only display the number of posts from a certain category starting at a certain date?
I’ve tried something like this but it doesn’t work:
<?php
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE term_id = '4' AND post_date >= '2014-01-01 00:00:00' " );
echo "<p>User count is {$user_count}</p>";
?>
What am I doing wrong?
Use wordpress native WP-Query:
$args = array(
'post_type' => 'post',
'date_query' => array(
'year ' => 2015,
),
'cat' => 5,
'posts_per_page'=> -1
);
$query = new WP_Query( $args );
$numberOfPosts = $query->post_count;
$numberOfPosts should hold the number you are looking for. Just paste this where you used your original code which you've shared with us.
Read more here: https://codex.wordpress.org/Class_Reference/WP_Query
Excerpt from the above mentioned url:
posts_per_page (int) - number of post to show per page (available with Version 2.1, replaced showposts parameter). Use 'posts_per_page'=>-1 to show all posts (the 'offset' parameter is ignored with a -1 value). Set the 'paged' parameter if pagination is off after using this parameter. Note: if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. To reimpose the limit, try using the 'post_limits' filter, or filter 'pre_option_posts_per_rss' and return -1
You can find a bunch of other options there aswell to tweak your query, to get the desired result. This should give the result you want for now.

Codeigniter mysql where not equal to query

Mysql codeigniter query is not working properly.
Suppose if mysql table looks like this:
user_id|user_name
1|john
2|alex
3|sam
Here user_name is unique
The following query should return false if user_name=john and user_id=1 and true if say user_name=john and user_id=2.
$this->db->get_where('user', array('user_name' => $name,'user_id !=' => $userid));
But it returns true in the case user_name=john and user_id=1.
Can anyone suggest me an alternative way of querying not equal to.
print($this->db->last_query()) gives:
SELECT * FROM (user) WHERE user_name = 'john' AND user_id != '1'
Why dont you use simple $this->db->query('your query');
Simply try this, Add the desired condition in the where function.
$this -> db -> where('invitee_phone !=', $user_phone);
You can go follwoing way too. It work for me
$total = 5;
$CI = get_instance();
$CI->load->database();
$CI->db->order_by('id','asc');
$topusers = $CI->db->get_where('users',array('user_type != 1 && `status` =' => 1),$total,0);
echo $CI ->db ->last_query();
die;
and if still not work for you can go with #rohit suggest: $this->db->query('your query');
Type 1:
Using ->where("column_name !=",$columnname) is fine for one column.
But if you want to check multi columns, you have to form an array inside where clause.
Like this
$whereArray = array(
"employee_name" => $name,
"employee_id !=" => $id,
);
$this->db->select('*')->from('employee')->where($whereArray);
Type 2:
We can just write exactly what we want inside where.
Like
$thi->db->where(("employee_id =1 AND employee name != 'Gopi') OR designation_name='leader#gopis clan'");
Type 2 is good for working with combining queries, i mean paranthesis "()"
you can follow this code:
$query = $this->db->select('*')->from('employee')->where('user_name', $name)->where('user_id !=', $userid)->get();
$last_query = $this->db->last_query();
$result = $query->result_array();
if you pass $name = 'john' and $userid = '1' then it return empty array.
The problem with using $this->db->query('your query'); is that it is not portable. One of the most important reasons to embrace the query builder methods is so that no matter what database driver you use, CodeIgniter ensures that the syntax is appropriate.
If a bit of discussion was possible, I'd probably like to hear why you need composite primary identifiers in your table and I'd like to see what your table schema looks like. However, I think the time for discussion has long passed.
Effectively, you want to return a boolean result stating the availability of the combination of the username AND the id -- if one is matched, but not both, then true (available).
To achieve this, you will want to search the table for an exact matching row with both qualifying conditions, count the rows, convert that integer to a boolean, then return the opposite value (the syntax is simpler than the explanation).
Consider this clean, direct, and portable one-liner.
return !$this->db->where(['user_name' => $name,'user_id' => $userid])->count_all_results('user');
this will return false if the count is > 0 and true if the count is 0.

CakePHP: How can I use a "HAVING" operation when building queries with find method?

I'm trying to use the "HAVING" clause in a SQL query using the CakePHP paginate() method.
After some searching around it looks like this can't be achieved through Cake's paginate()/find() methods.
The code I have looks something like this:
$this->paginate = array(
'fields' => $fields,
'conditions' => $conditions,
'recursive' => 1,
'limit' => 10,
'order' => $order,
'group' => 'Venue.id');
One of the $fields is an alias "distance". I want to add a query for when distance < 25 (e.g. HAVING distance < 25).
I have seen two workarounds so far, unfortunately neither suit my needs. The two I've seen are:
1) Adding the HAVING clause in the "group" option. e.g. 'group' => 'Venue.id HAVING distance < 25'. This doesn't seem to work when used in conjunction with pagination as it messes up the initial count query that is performed. (ie tries to SELECT distinct(Venue.id HAVING distance < 25) which is obviously invalid syntax.
2) Adding the HAVING clause after the WHERE condition (e.g. WHERE 1 = 1 HAVING field > 25) This doesn't work as it seems the HAVING clause must come after the group statement which Cake is placing after the WHERE condition in the query it generates.
Does anyone know of a way to do this with CakePHP's find() method? I don't want to use query() as that would involve a lot of rework and also mean I'd need to implement my own pagination logic!
Thanks in advance
You have to put it with the group conditions. like this
$this->find('all', array(
'conditions' => array(
'Post.length >=' => 100
),
'fields' => array(
'Author.id', 'COUNT(*) as Total'
),
'group' => array(
'Total HAVING Total > 10'
)
));
Hope it helps you
I used the following trick to add my own HAVING clause at the end of my WHERE clause. The "dbo->expression()" method is mentioned in the cake sub-query documentation.
function addHaving(array $existingConditions, $havingClause) {
$model = 'User';
$db = $this->$model->getDataSource();
// Two fun things at play here,
// 1 - mysql doesn't allow you to use aliases in WHERE clause
// 2 - Cake doesn't allow a HAVING clause separate from a GROUP BY
// This expression should go last in the WHERE clause (following the last AND)
$taut = count($existingConditions) > 0 ? '1 = 1' : '';
$having = $db->expression("$taut HAVING $havingClause");
$existingConditions[] = $having;
return $existingConditions;
}
As per the manual, CakePHP/2 supports having at last. It was added as find array parameter on version 2.10.0, released on 22nd July 2017.
From the 2.10 Migration Guide:
Model::find() now supports having and lock options that enable you to
add HAVING and FOR UPDATE locking clauses to your find operations.
Just had the same problem. I know, one is not supposed to modify the internal code but if you open the PaginatorComponent and you modify line 188:
$count = $object->find('count', array_merge($parameters, $extra));
to this:
$count = $object->find(
'count',
array_merge(array("fields" => $fields),$parameters, $extra)
);
Everything will be fixed. You will be able to add your HAVING clause to the 'group' and the COUNT(*) won't be a problem.
Or, make line:
$count = $object->paginateCount($conditions, $recursive, $extra);
to include the $fields:
$count = $object->paginateCount($fields,$conditions, $recursive, $extra);
After that, you can "override" the method on the Model and make sure to include the $fields in the find() and that's it!, =P
Here is another idea that doesn't solve the pagination issue, but it is clean since it just overrides the find command in AppModel. Just add a group and having element to your query and this will convert to a HAVING clause.
public function find($type = 'first', $query = array()) {
if (!empty($query['having']) && is_array($query['having']) && !empty($query['group'])) {
if ($type == 'all') {
if (!is_array($query['group'])) {
$query['group'] = array($query['group']);
}
$ds = $this->getDataSource();
$having = $ds->conditions($query['having'], true, false);
$query['group'][count($query['group']) - 1] .= " HAVING $having";
CakeLog::write('debug', 'Model->find: out query=' . print_r($query, true));
} else {
unset($query['having']);
}
}
return parent::find($type, $query);
}
Found it here
https://groups.google.com/forum/?fromgroups=#!topic/tickets-cakephp/EYFxihwb55I
Using 'having' in find did not work for me. Instead I put into one string with the group
" group => product_id, color_id having sum(quantity) > 2000 " and works like a charm.
Using CakePHP 2.9

Can I use subqueries in a 'containable' condition?

In my CakePHP I have ModelA which hasMany ModelB. ModelB has an int value Q.
Can I query ModelA and use containable to ensure that only those ModelB records with the maximum value for Q?
I've tried this:
$this->ModelA->contain(array(
'ModelB.Q =(SELECT MAX(ModelB.Q) FROM modelb ModelB WHERE ModelA_id = ' . $id . ')'
));
But it throws a MySQL error because CakePHP interprets the right hand side of that equality operator as a field (at least I think that's why) and so dots it.
... WHERE `Draw`.`round` =.(SELECT MAX.(`Draw`.`round`) ...
Is there a way to do this? I'd prefer not to have to drop down into $query() mode, if at all possible.
EDIT OK, after trying to follow the advice on the page that api55 suggested, I have this code:
$dbo = $this->Tournament->getDataSource();
$conditionsSubQuery['"Draw"."tournament_id"'] = $id;
$maxRounds = $dbo->buildStatement(array(
'fields' => array('MAX(Draw.round) AS prevRound'),
'table' => $dbo->fullTableName($this->Tournament->Draw),
'alias' => 'Draw',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQuery,
'order' => null,
'group' => null
),
$this->Tournament
);
$maxSubQuery = ' "Draw"."round" = (' . $maxRounds . ') ';
$maxSubQueryExpression = $dbo->expression($maxSubQuery);
$this->Tournament->contain(array(
'Entrant.selected = 1',
$maxSubQueryExpression
));
$tournament = $this->Tournament->read(null, $id);
But when it runs, it gives me 7 notice/warnings. The first 6 are to do with an object being passed instead of a string:
preg_match() expects parameter 2 to be string, object given
And 6 variations on this:
Object of class stdClass to string conversion
The last is less clear:
Model "Tournament" is not associated with model ""
I suspect I'm being colossally stupid, but there we go.
The contain uses conditions as a normal find, a subquery can be generated and put in conditions. So you should be able to do this as well. Try the subquery part in here and tell me how did it go ;)
This way of generating subqueries for conditions shouldn't fail :D since is the cakephp way.
If you got an error or something comment the answer to see if i can help.

Insert a time + n in mySQL using Zend_db_table!

$data = array (
'next' => "NOW() + 5",
'interval' => $dom["USER"][0]["STATUSES_COUNT"][0]["data"],
'good' => $good,
'tries' => $p->tries + 1
);
$where = $service->getAdapter()->quoteInto('id = ?', $p->id);
$service->update($data, $where);
to insert something to a database using PHP on zend and mySQL.
The "next" => "NOW()" wont work. I could put the CURRENT_TIMESTAMP as default value, but what i actually want is to insert the timestamp refering this moment, plus some time.
I could rewrite some parts of the program to use pure php dates(instade of pure mySQL dates). Dont know what is best, or what should i do. Do you know how i could make this update work with mySQL doing the timing?
I solved it with the next statement, very usefull:
'next' => new Zend_Db_Expr('TIMESTAMPADD(MINUTE,1,NOW())'),