Insert a time + n in mySQL using Zend_db_table! - mysql

$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())'),

Related

Wordpress - use $wpdb->update and limit 1

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);
});

Novice: How to do update with id in cakephp2 mysql?

I'm new to cakephp2 and mysql and I want to create a mysql query to update the data with a id that has been passed in.I'm a very slow learner so I would want some help.
$this->User->updateAll(
array(
'User.checked_count' => '`User`.`checked_count` + 1',
'User.modified' => "'" . date('Y-m-d H:i:s') . "'"
),
array(
'User.username' => $username,
)
);
PS. How to get the results from the query above and use foreach loop? It doesn't work, so Im having a little trouble with it .
In cakePhp 2.x you can do it like that:
1) Below is simple update using save() function, where you pass id as reference and cake automatically updates the table when id is set else will insert the data in new row:
$this->User->id = $Id;
$this->User->save($this->request->data);
2) If you want one or more records in a single call to get updated use updateAll() function:
$this->User->updateAll(
array('User.checked_count' => $count),
array('User.id ' => $userId)
);
Try this code
$this->User->id = $passedId;
$this->User->save($this->data);
In above code If user_id is present then It update user data other wise it save userData.

Wordpress custom table query conflict?

I am going mad....
I have custom table: wp_wwiz_customers
and among other columns there i have user_status and when I try to update status using wp db query like this:
$wpdb->update('wp_wwiz_customers', array( 'user_status' => 'CRAZY' ),array('id' => $entryid)
and I am using exit( var_dump( $wpdb->last_query ) ); to see response is:
string 'UPDATE `wp_wwiz_customers` SET `user_status` = 0 WHERE `id` = '4'' (length=65)
Ok, my query seems normal, so why in the world WP puts 0 instead of value.... and I tried to change name of table user_status to user_statusss like in this query and there I have expected result:
$wpdb->update('wp_wwiz_customers', array( 'user_statusss' => 'CRAZY' ),array('id' => $entryid)
// Results as:
string 'UPDATE `wp_wwiz_customers` SET `user_statusss` = 'CRAZY' WHERE `id` = '4'' (length=73)
Ok, so what is my best bet here ? I just can't change column name right now... is there any option to make this work if this is conflict.... ? ...or maybe I am missing something ?
I am again faster to ask than to read documentation....
obviously (sometimes) it is mandatory to place format of data you are entering....
$wpdb->update('wp_wwiz_customers', array( 'user_status' => 'CRAZY' ),array('id' => $entryid),array('%s')
",array('%s')" part tells WP that this is string... and it works now.

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

codeigniter mysql query problem

I execute a simple insert query, however this insert is done multiple times sometimes unexpectedly. The code for insert is :
$query=$this->db->query("INSERT INTO clientaccesshistory (jobid, clientid,firstname,lastname,clientname,menu,submenu,starttime) VALUES ('$time','$userID','$firstname','$lastname','$clientname','Monitor/Verify', '$this->job_name',current_timestamp() )");
When i look in the database though this information is sometimes there 3 times, sometimes its just once like it is supposed to be. I think this is some issue with connecting to mysql, and then retries till it inserts three times?
I tested the front end to see if the function is actually be called more than once by putting an alert there, but no problem there whatsoever.
Your code almost certainly has to be in a variable loop of some kind. This code, like wonk says, will not add more than one record, ever.
This won't be of much help, but you can try using this-
$arr = array(
jobid => $time,
clientid => $userID,
firstname => $firstname,
lastname => $lastname,
clientname => $clientname,
menu => 'Monitor/Verify',
submenu => $this->job_name,
starttime => current_timestamp()
);
$this->db->insert('clientaccesshistory', $arr);