I presume it means double but what does it mean in general?
$wpdb->delete(
"data",
[ 'id' => $id ],
[ '%d' ]
);
I get that I'm deleting from table data using array id => id but what is the %d for?
Why am I asking? well, I'd like to do some bulk updates as shown through the features built in with wp_list_table as shown through this tutorial. As I've looked around for that first link I found a few more sources on how to fix my table - I'm just trying do multiple operations and I'm stuck with bulkupdater
its to identify the type of data to be deleted think where=%d which means interger
others include:
%d - interger (just to make it clear)
%f - float
%s - string
so your code
$wpdb->delete(
"data",
[ 'id' => $id ],
[ '%d' ]
);
Is only going to delete an id where the id string is an integer e.g. 43 not if a43
You can have obviously a few types in an array, but they need to match the order of the data array (i.e. array('id'=>$id, 'numval'=>$num) ,array(integer, integer) )
Related
I would like to find out the number of affected (inserted) rows after inserting into the table. I didn't figure out how to do it in the documentation. The update returns the number of affected rows. The insert returns Nette\Database\Table\ActiveRow
How do I get it?
$affected = $context->table('author')->insert([
[
'name' => 'Sansa Stark',
'born' => null
], [
'name' => 'Arya Stark',
'born' => null
]
]);
bdump($affected); // Nette\Database\Table\ActiveRow - I need the number of inserted records
Nette Database Explorer doesn't return count after insert(). It is not useful information as long as you can count data before insert by yourself.
$data = [...];
$count = count($data);
$context->table('author')->insert($data);
It works only with update and delete as is mentioned in documentation.
$count = $context->table('author')
->where('id', 10)
->delete();
It might be possible with getRowCount() over query in Nette Database Core
Nette Database Core is built upon PDO. Alas, the authors tend to create their own objects instead of extending PDO, which makes such elementary operations tedious:
// get Nette ResultSet object
$resultSet = $this->database->query("INSERT/UPDATE/DELETE...");
// get original PDOStatement object
$pdoStatement = $resultSet->getPdoStatement();
// get the affected rows from PDO object (instead of $resultSet->rowCount())
$pdoStatement->rowCount();
A word of warning for those considering Nette for production: There is no real documentation, only cook books and autogenerated PHPDoc which just prints names without any explanation.
I am using Omines Symfony DataTable Bundle https://omines.github.io/datatables-bundle/#doctrine-orm to organize my event table.
I am unable to search on my "Début" and "Fin" columns which are of type Datetime Column. I'm guessing because since these are DateTime objects I'm guessing it can't find a match.
mytable
If I type "08/19/2020" it doesn't find any results for me.
Here: https://datatables.net/forums/discussion/44218/how-do-i-search-on-a-datetime-column it advises to format the date on the server side, so I tried that (of course j 've installed the doctrine extensions to be able to use date_format):
->createAdapter(ORMAdapter::class, [
'entity' => Event::class,
'query' => function (QueryBuilder $builder) use ($eventStatus) {
$builder
->select('e')
->addSelect('DATE_FORMAT(e.startDate, "%d/%m/%Y")')
->addSelect('ca')
->addSelect('ci')
->addSelect('u')
->from(Event::class, 'e')
->join('e.category', 'ca')
->join('e.city', 'ci')
->join('e.user', 'u')
->andWhere('e.status = :status')
->setParameter('status', $eventStatus)
->orderBy('e.id', 'DESC')
;
},
])
I also changed my dateStart column to TextColumn:
->add('startDate', TextColumn::class, ['label' => 'Début', 'field' => 'e.startDate', 'render' => function($value, $context) {
return sprintf(
'%s<br>
%s',
$value,
$context->getStartAt()->format('H\hi'),
);
}])
And I have this error:
Uncaught PHP Exception Doctrine \ ORM \ Query \ QueryException: "[Syntax Error] line 0, col 34: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '"' "
I do not see where the problem is.
Thanks for your help.
It's difficult to tell from the question you are asking, but there are certain things that look problematic in your code.
First, you use a custom query, but you don't use any WHERE clause with the date.
Second, your formatting of the column is not named. The result can't be accessed since it doesn't have a name. You can name it with the keyword AS:
->addSelect('DATE_FORMAT(e.startDate, "%d/%m/%Y") AS startDateFormatted')
Third, you use joins and then you shouldn't use ORMAdapter but FetchJoinORMAdapter (this will help you solve problems with pagination when using joins).
In my opinion, you shouldn't try to format the startDate in the query, but check the documentation and use a Criteria
https://omines.github.io/datatables-bundle/#doctrine-orm
I'm trying to query events where 'total > 500', but it doesn't work correctly.
Microanalysis for field total says it's type is long.
I imported from CSV, than mutated to integer
mutate {
convert => [ "total", "integer" ]
}
Finally found the solution
total:>500
More info at Lucene Query String Elasticsearch "less than or equal to"[URI Search]
I use JetPack stats to follow the stats for my blog. I would like to extract the top 10 most-viewed posts for a given period (e.g. last month).
I used the WordPress stats plugin API before which worked nicely, but after upgrade to JetPack this doesn't work anymore.
Is there an API which allows me to query the number of view counts for a post?
Inside the Database
This option is recorded in the database and is used by the Dashboard widget:
get_option( 'stats_cache' );
It returns an array like this:
array(
['7375996b7a989f95a6ed03ca7c899b1f'] => array(
[1353440532] => array(
[0] => array(
['post_id'] => 0
['post_title'] => 'Home page'
['post_permalink'] => 'http://www.example.com/'
['views'] => 1132
)
[1] => array(
['post_id'] => 4784
['post_title'] => 'Hello World!'
['post_permalink'] =>
['views'] => 493
)
/* till item [9] */
Querying WordPress.com
It is possible to call the following Jetpack function:
if( function_exists( 'stats_get_csv' ) ) {
$top_posts = stats_get_csv( 'postviews', 'period=month&limit=30' );
}
Which returns:
array(
[0] => array(
['post_id'] => 0
['post_title'] => 'Home page'
['post_permalink'] => 'http://www.example.com/'
['views'] => 6806
)
[1] => array(
['post_id'] => 8005
['post_title'] => 'Hello World!'
['post_permalink'] =>
['views'] => 1845
)
/* till item [29] */
Function get_stats_csv
/plugins/jetpack/modules/stats.php
The function get_stats_csv calls http://stats.wordpress.com/csv.php. If we visit this address, we get this response:
Error: api_key is a required parameter.
Required parameters: api_key, blog_id or blog_uri.
Optional parameters: table, post_id, end, days, limit, summarize.
Parameters:
api_key String A secret unique to your WordPress.com user account.
blog_id Integer The number that identifies your blog.
Find it in other stats URLs.
blog_uri String The full URL to the root directory of your blog.
Including the full path.
table String One of views, postviews, referrers, referrers_grouped,
searchterms, clicks, videoplays.
post_id Integer For use with postviews table.
end String The last day of the desired time frame.
Format is 'Y-m-d' (e.g. 2007-05-01)
and default is UTC date.
days Integer The length of the desired time frame.
Default is 30. "-1" means unlimited.
period String For use with views table and the 'days' parameter.
The desired time period grouping. 'week' or 'month'
Use 'days' as the number of results to return
(e.g. '&period=week&days=12' to return 12 weeks)
limit Integer The maximum number of records to return.
Default is 100. "-1" means unlimited.
If days is -1, limit is capped at 500.
summarize Flag If present, summarizes all matching records.
format String The format the data is returned in,
'csv', 'xml' or 'json'.
Default is 'csv'.
Non-working query example:
?api_key=123456789abc&blog_id=155&table=referrers&days=30&limit=-1&summarize
Result format is csv with one row per line and column names in first row.
Strings containing double quotes, commas, or "\n" are enclosed in double-quotes.
Double-qoutes in strings are escaped by inserting another double-quote.
Example: "pet food" recipe
Becomes: """pet food"" recipe"
Developers, please cache the results for at least 180 seconds.
In Drupal, I can execute a SQL as follows:
$query_object = db_query("SELECT * FROM {nodes}");
If I know the query returns only a single result (so only 1 row and 1 column), I can directly fetch it with:
$result = db_result($query_object);
If I got multiple results, I need to loop through them with something like:
$rows[] = array();
while (($row = db_fetch_object($query_object) != FALSE) {
$rows[] = $row;
}
I'm wondering if there is an easier way to do that? Is there a way that I can transfer all results into an array with a single statement? Or isn't that working, because db_result returns a cursor-like object, where you can only fetch a single row each time?
Not in Drupal 6.
In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:
<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>
In Drupal 7, you can also use:
db_query('QUERY')->fetchAll(PDO::FETCH_ASSOC);
I do always something like this ( just a simple exemple) :
$query = db_query("SELECT nid
FROM {from}
WHERE blallala
",
$tab_arg
);
if ($query->rowCount() == 0) {
$output=t('no result')
} else
{
foreach($query as $result)
{
$tab_res[]=$result;
}
foreach($tab_res as $res)
{
$output.=$res->nid;
}
}
One can also use db_fetch_array($result), where $result =db_query($queryString). As explained from the Drupal documentation:
[It returns] ...an associative array representing the next row of the result, or
FALSE. The keys of this object are the names of the table fields
selected by the query, and the values are the field values for this
result row.