I can't figure the syntax for this request :
UPDATE my_table SET is_read ='1' WHERE my_date < DATE_SUB(NOW(), INTERVAL 2 DAY
'my_date
for using with wpdb-> update
I have this :
wpdb->update('my_table', array('is_read' => '1'), array('my_date', ... and then I don't know
Need some help. Thanks in advance :)
Example to use SQL queries directly with wpdb:
function setAsRead($days_interval){
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare("UPDATE my_table SET
is_read ='1' WHERE my_date < DATE_SUB(NOW(), INTERVAL %d DAY)",
$days_interval));
return $result;
}
//use
setAsRead(2);
Related
I ran this query in Wordpress DB and found out that Booking dates are stored in some coded way.
SELECT post_id, meta_id, post_title, meta_key, meta_value
FROM a40443635734677.wp_7n2ncdd4yn_postmeta, a40443635734677.wp_7n2ncdd4yn_posts
where post_id = ID and post_type = 'estate_property'
and meta_key in ('property_price', 'cancellation', 'booking_dates',
'prop_featured', 'min_days_booking') and meta_key = 'booking_dates' and post_id = 248
order by post_id;
Output: a:2:{i:1600646400;i:374;i:1600732800;i:374;}
From UI, it shows that booking dates are sept-21-2020 to sept-23-2020.
how to decode the data from DB (a:2:{i:1600646400;i:374;i:1600732800;i:374;}) to these dates?
You can use unserialize() to convert it into an array.
$dbdata = 'a:2:{i:1600646400;i:374;i:1600732800;i:374;}';
$dbdata = unserialize($dbdata);
//result
array (
1600646400 => 374,
1600732800 => 374,
)
Then use PHPs DateTime to convert to human readable format e.g.
$returnDate = date('d.m.Y H:i:s', 1600646400);
//result
21.09.2020 02:00:00
The larger set of numbers you showed us look like seconds since the Epoch (January 1, 1970). You could use MySQL's FROM_UNIXTIME function convert these epoch values to a bona-fide human readable date. For example:
SELECT FROM_UNIXTIME(1600646400); -- 21.09.2020 02:00:00
That is serialized data. Use PHPs built in unserialize( your output variable here ). You'll get an array since the serialized data is an array (a:2 means array with two indexes).
The date is in UNIX time. You can use PHPs DateTime to convert to human readable format.
$output = SELECT post_id, meta_id, post_title, meta_key, meta_value
FROM a40443635734677.wp_7n2ncdd4yn_postmeta, a40443635734677.wp_7n2ncdd4yn_posts
where post_id = ID
and post_type = 'estate_property'
and meta_key in ('property_price', 'cancellation', 'booking_dates', 'prop_featured', 'min_days_booking') and meta_key = 'booking_dates'
and post_id = 248 order by post_id;
// Unserialize the data.
$unserialized = unserialize($output);
// Get the date for each array key. The date is the $key, so you pass that to the php date function.
foreach( $unserialized as $key => $date ) {
echo date('M-d-Y', $key ) . "\n";
}
This will output Sept-20-2020 and Sept-21-2020 with the data you supplied.
In my Wordpress plugin I have code snippets that look like this:
$total = $wpdb->get_var($wpdb->prepare(
"
SELECT SUM(Amount)
FROM $table_name
WHERE Account = $user_id AND Timestamp > {$balance['Timestamp']}
",NULL
));
It was working very well for years, but after I recently updated Wordpress to 5.0 I get many errors like this:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function wpdb::prepare(), 1 passed in (...)/pluginfile.php on line 753 and exactly 2 expected in /wp-includes/wp-db.php:1222
Through my research I found that I need to use %s and %d in the wp prepare function but I didn't figure out how to apply it properly to the code above.
We use the 'prepare' method to make sure we're not sending an illegal operation or any illegal characters.
Try modifying your code to the following:
$total = $wpdb->get_var($wpdb->prepare(
"
SELECT SUM(Amount)
FROM $table_name
WHERE Account = %d AND Timestamp > %d
",
$user_id, $balance['Timestamp']
));
Both User ID and a timestamp are integers (whole numbers) so we would use %d.
Possible format values: %s as string; %d as integer (whole number); and %f as float.
For anybody that might run into a similar problem: with the help of the comment above by #entreprenerds I was able to fix the code as follows:
$total = $wpdb->get_var($wpdb->prepare(
"
SELECT SUM(Amount)
FROM $table_name
WHERE Account = %d AND Timestamp > %d
",$user_id, $balance['Timestamp']
));
Thanks!
SELECT address
FROM user_address
WHERE username = '$user->name'
ORDER BY time DESC
LIMIT 1
Here is the SQL query that I can understand. How is it possible to convert it into Drupal's 7 PHP? I'm trying to figure that out for a day, and I tried different approaches, but it seems that I am just bad in that.
You can use db_select :
$results = db_select('user_address', 'ua')
->fields('ua', array('address'))
->condition('ua.username', $user->name, '=')
->orderBy('ua.time', 'DESC')
->range(0,1)
->execute()
->fetchAll();
var_dump($results);
Otherwise you can use db_query if you want to write entire SQL :
$results = db_query("SELECT address
FROM user_address
WHERE username = :username
ORDER BY time DESC
LIMIT 1 ", array(':username' => $user->name))->fetchAll();
var_dump($results);
Finally you can use db_query_range :
$page = 0;
$limit = 1
$results = db_query_range("SELECT address
FROM user_address
WHERE username = :username
ORDER BY time DESC",
$page * $limit,
$limit,
array(':username' => $user->name))
->fetchAll();
var_dump($results);
Try this:
$result = db_select('user_address', 'ua')
->fields('ua', array('address'))
->condition('ua.username', $user->name)
->execute()
->fetchAll();
For that we use db_select() or db_query() - first one preferable.
$query = db_select('user_address', 'u');
// Add condition and fields
$query->condition('u.username', ‘james’)
$query->fields('u’ array('u.address'));
// execute it
$result = $query->execute();
foreach ($result as $record) {
// Do something with each $record
}
For more see
https://www.drupal.org/docs/7/api/database-api/dynamic-queries/introduction-to-dynamic-queries.
update: see condition portion. Also, you can put this in a module or php executable area of your site or via drush command line.
Change the username James to match your need
$result = $result = db_select('usr_address','u')
->fields('u',array('address','uid'))
->range(0,1)
->orderby('time', 'DESC')
->condition('u.uid',$uid,'=')
->execute();
here is how it actually worked.
Thank you for your suggestions, but at the end I made it. By myself. Well, kinda ;D
I am trying to build a query that retrieves all the most recent and upcoming activities from database.
The entity activity has a field named date of type DateTime. So in my repository I was thinking of building something like this:
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, NOW())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
Unfortunately I get the following error:
[Syntax Error] line 0, col 59: Error: Expected end of string, got '('
The Dql that is generated by my query:
SELECT a FROM MyBundle\Entity\Activity a ORDER BY DATEDIFF( a.date, NOW()) ASC
I also tried installing beberlei/DoctrineExtensions, but either it is not working or I was unable to configure it correctly.
Anyone has any suggestion?
Thanks in advance
date_diff si already implemented as Doctrine DQL statement as described here
for use as ordering statement I suggest you to use the HIDDEN select keyword as explained in this article
So your DQL is like this:
SELECT
a,
DATE_DIFF( a.date, CURRENT_TIMESTAMP() ) AS HIDDEN score
FROM MyBundle:Entity a
ORDER BY score
And add the max result on the query. Let me know if you need help to adapt as query builder statement
Hope this help
Why don't you just use
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, CURRENT_TIMESTAMP())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
?
I have this sql query:
SELECT * from gift WHERE NOW() >= `validbegin` AND NOW() <= `validend` ORDER BY `points`n ASC
I need to transform it to a Symfony 2 query to fetch the data to an object call Gift. So far I have this:
$query = $giftRepository->createQueryBuilder('p')
->where('NOW() >= validbegin AND NOW() <= p.validend')
->orderBy('p.points', 'ASC')
->getQuery();
$gifts = $query->getResult();
But that gave me:
[Syntax Error] line 0, col 53: Error: Expected known function, got
'NOW'
Any idea?
ps. Also tried p.NOW()
Try this :
$query = $giftRepository->createQueryBuilder('p')
->where(':now >= validbegin AND :now <= p.validend')
->setParameter('now', new \DateTime())
->orderBy('p.points', 'ASC')
->getQuery();
$gifts = $query->getResult();
You generate the field from php, then doctrine will automatically convert it to a mysql timestamp