Additional information in one API call - facebook

Given below my code outputs number of Posts, Likes, Comments, and Shares for my Facebook page. It considers only present one week data. This is done using fql qpproach (I know fql is deprecated but my code works fine because the app I am using is an older app). I have few questions to ask and need help in getting that done:
I need help in converting this code using the latest api approach so that it can work on newly created apps.
The code outputs total number of likes, comments and shares just fine but is it possible to get the usernames of those who liked, commented and share the posts of my page in the past one week and update the values in a database table? If yes, how?
If point #2 is possible, can this be done in one API call?
Appreciate some assistance here.
<?php
require('config.php');
session_start();
?>
<?php
$facebook = new Facebook(array(
'appId' => '012myappid210',
'secret' => 'abc012myappsecret210cba',
'cookie' => true,
));
$token=$_SESSION['token'];
$pageid='88978302070'; //(my facebook page id)
$d=strtotime("now");
$d2=strtotime('now - 7 days');
$fqlAPIParams = array(
'method' => 'fql.query',
'query' =>'
SELECT post_id,comments,message,likes,created_time,share_count
FROM stream
WHERE actor_id = '.$pageid.' AND
source_id = '.$pageid.' AND created_time <= '.$d.' AND created_time >= '.$d2.'
LIMIT 250' ,
'access_token'=>$token
);
$result = $facebook->api($fqlAPIParams);
$postCount = 0;
$likescount=0;
$commentscount=0;
$sharescount=0;
foreach($result as $post)
{
$shares=$post['share_count'];
$likes=$post['likes']['count'];
$comments=$post['comments']['count'];
$likescount+=$likes;
$commentscount+=$comments;
$sharescount+=$shares;
$postCount++;
}
echo "Post " . $postCount . " Likes " . $likescount . " Comments " . $commentscount . " Shares " . $sharescount;
?>
Here is the output of the code you suggested:
Post: Likes: 25 Comments: 5 Shares: 30
Post: Likes: 0 Comments: 0 Shares:
Post: Likes: 25 Comments: 25 Shares: 54
PageID 88978302070 has 2 posts in the past 30 days (on 31st Oct and 21st Oct)
Few changes what I made:
1. I changed 'until' to 'since' 88978302070/posts?fields=likes,comments,shares&since=-30 days.
2. I changed the inner loop because one more issue I found was... instead of $post['likes'] and $post['comments'], it should have been $post['likes']['data'] and $post['comments']['data']
Code is working but Now the problem is:
1. It lists three posts whereas the page has only 2. One additional post is shown with 0 likes, 0 shares, 0 comments. Not sure where it is coming from.
2. Like count is incorrect. It only displays and lists a maximum of 25 likes and comments. I tried to put a limit of 999999 but it displays maximum 1000. Is there any solution to this? Actual like count for the two posts are 24483
3. Comment count is incorrect. It has to be 90 but the code lists 25+5=30
4. It does not lists usernames of those who shared the posts.

Without using FQL, you can do the following:
$d2 = strtotime( '- 7 days' );
$result = $facebook->api( $page_id . '/posts?fields=likes,comments,shares&until=' . $d2 );
foreach ( $result['data'] as $post ) {
echo 'Post: ' . $post['id'] . ' Likes: ' . count( $post['likes']['data'] ) . ' Comments: ' . count( $post['comments']['data'] ) . ' Shares: ' . $post['shares']['count'] . '<br/>';
}
The above API result also includes the name and IDs for all the users who have liked / commented on each post. You can do another foreach loop in the code to cycle through the likes / comments and update your database accordingly.
Example:
// main loop to cycle through posts
foreach ( $result['data'] as $post ) {
// inner loop to cycle through likes
foreach ( $post['likes'] as $like ) {
echo 'User: ' . $like['id'] . ' Name: ' . $like['name'];
// code to check / update db here
}
}
Running the above code for page 177526890164 (Narendra Modi) using limit=2 returns the following. If you are seeing a blank page or an error, you're clearly doing something wrong:
The best way to test would be to make the API call, and then add print_r( $result ) after to see if Facebook returns any data. If it's empty, there is something wrong with your API call.

Related

how to use wp_update_post with multiple posts ids

please i have this code which set the date for the post id 144600, but please need to add 2 id's to be in the code these ids 456 and 874 , please how to add them to the code
$id = 144600;
$date_time = "2022-10-31 23:59:59";//[Y-m-d H:i:s]
wp_update_post(
array (
'ID' => $id,
'post_date' => $date_time,
'post_date_gmt' => get_gmt_from_date( $date_time )
)
);
please i have this code which set the date for the post id 144600, but please need to add 2 id's to be in the code these ids 456 and 874 , please how to add them to the code

PhpOrient query returns negative Rid-s by default

I'm trying to retrieve a simple graph consisting of some Assignments that are linked to each other, however after querying one set of those assignments, the Rid-s that are returned are all negative and have nothing to do with the Rid-s in the database, so I can't run other query-s based on those Rid-s, how should I go around this, or am I doing something wrong?
Here is the code snippet responsible:
$records = $this->client->queryAsync('select rID, value, schedule, priority, type from Assignment where type = 5');
foreach ($records as $record)
{
$id = $record->getRid();
$rid = $id->__toString();
$return[$rid] = $this->client->query('TRAVERSE out("Assignment") FROM ' . $rid . ' WHILE $depth <= 5');
}
and the error that I receive:
com.orientechnologies.orient.core.exception.ORecordNotFoundException: The record with id '#-2:0' was not found
However in the database the first id is: #18:0
Hi Pirate's Lost Pearl,
is probably a problem with the transactions, orientdb makes negative RID-s when they are temporary. After the commit, the RID-s are changed to positive, here the doc
There are a couple of errors in your code:
First off you should change your __toString(); into _toString(); using a single underscore.
Then fix the $this->client->query by either switching quotation marks at the end such as " WHILE $depth <= 5" or concatenate the variable while keeping the same quotes ' WHILE ' . $depth . ' <= 5'.
OrientDB Docs | getRid()

how to get specific rows page number in pagination

I have a question on MySQL paging. A user's record is displayed on a table with many other user's record. and the table is sorted/paged. Now I need to display the page that containing the user's row directly after the user login. How can I achieve this?
create table t_users (id int auto_increment primary key, username varchar(100)); insert t_users(username) values ('jim'),('bob'),('john'),('tim'),('tom'), ('mary'),('elise'),('karl'),('karla'),('bob'), ('jack'),('jacky'),('jon'),('tobias'),('peter');
I searched the google but not found answer so please help
There are two steps for this:
1. Determine the row's position in your sorted table.
Copied and tweaked from: https://stackoverflow.com/a/7057822/2391142
Use this SQL...
SELECT z.rank FROM (
SELECT id, #rownum := #rownum + 1 AS rank
FROM t_users, (SELECT #rownum := 0) r
ORDER BY id ASC
) as z WHERE id=1;
...replacing the ORDER BY id ASC with whatever your actual sort order is. And replacing the number 1 in WHERE id=1 with the provided number in that index.php?u=id url.
2. Determine the page number based on the row's position.
Use this PHP to determine the needed page number...
$rows_per_page = 50;
$user_row_position = [result you got from step 1];
$page = ceil($user_row_position / $rows_per_page);
...replacing the 50 with whatever your real rows-per-page limit is, and putting the real SQL result in $users_row_position.
And voila. You'll have the destination page number in the $page variable and hopefully you can take it from there.
EDIT
After further discussion in the comments, use this bit of PHP:
$page = 0;
$limit = 10;
// If a user ID is specified, then lookup the page number it's on.
if (isset($_GET['u'])) {
// Check the given ID is valid to avoid SQL injection risks.
if (is_numeric($_GET['u'])) {
// Lookup the user's position in the list.
$query = mysqli_fetch_array(mysqli_query($link, "SELECT z.rank FROM (SELECT id, #rownum := #rownum + 1 AS rank FROM sites, (SELECT #rownum := 0) r WHERE online='0') as z WHERE id=" . $_GET['u']));
$position = $query[0];
if (is_numeric($position)) {
// Convert the result to a number before doing math on it.
$position = (int) $position;
$page = ceil($position / $limit);
}
}
}
// If a page number is specified, and wasn't already set by looking a user, then lookup the real starting row.
if ($page == 0 && isset($_GET['page'])) {
// Check your given page number is valid too.
if (is_numeric($_GET['page'])) {
$page = (int) $_GET['page'];
}
}
// Notice that if anything fails in the above checks, we just pretend it never
// happened and keep using the default page and start number of 0.
// Determine the starting row based off the page number.
$start = ($page - 1) * $limit;
// Get the list of sites for the provided page only.
$query = mysqli_query($link, "SELECT * FROM sites WHERE online='0' LIMIT " . $start . ", " + $limit);
while ($row = mysqli_fetch_array($query)) {
// Stuff to render your rows goes here.
// You can use $row['fieldname'] to extract fields for this row.
}

zend framework count the number of rows in mysql query

I am new to zend framework
I want to calculate number of rows in my query
this is my code:
$nm = new Zend_Db_Table('emp');
$row = $nm->fetchRow($nm->select()->where('id= ?', $a));
yes you can try in this way to get total number of rows return by your sql query.
$select = $this->select();
$select->where('id= ?', $a);
$result=$this->fetchAll($select);
if(empty($result)){
return false;
}else{
echo "Total number of users : -> ".count($result->toArray());
}
let me know if i can help you more.
If you are testing for the existance of a record by primary key then you can use $nm->find($a) and check for any results.
if you expect the result set to be small then you can do
$nm->fetchAll($nm->select()->where("id = ?", $a);
If you expect the result set to get big and all you are really after is the count then authoring a query that asks for the count of a field would probably make the most sense to keep the query from eating up a lot of server memory:
$row = $nm->getAdapter()->fetchRow("select count(*) as num_rows".
" from ".$nm->info(Zend_Db_Table_Row_Abstract::NAME).
" where ".$nm->getAdapter()->quoteInto("id = ?", $a));
echo "Users ".$row["num_rows"];
In Zend Framework 1, you can use count() function at the last of query for getting total number of rows in the table.
For example:
$row = $nm->fetchAll($nm->select()->where('id = ?', $a ))->count();
NOTE: This will only return total number of rows in the table. Output is Integer.

Having an SQL SELECT query, how do I get number of items?

I'm writing a web app in Perl using Dancer framework. The database is in sqlite and I use DBI for database interaction.
I'm fine with select statements, but I wonder is there a way to count selected rows.
E.g. I have
get '/' => sub {
my $content = database->prepare(sprintf("SELECT * FROM content LIMIT %d",
$CONTNUM));
$content->execute;
print(Dumper($content->fetchall_arrayref));
};
How do I count all items in the result without issuing another query?
What I want to achieve this way is showing 30 items per page and knowing how many pages there would be. Of course I can run SELECT COUNT (*) foo bar, but it looks wrong and redundant to me. I'm looking for a more or less general, DRY and not too heavy on database way to do so.
Any SQL or Perl hack or a hint what should I read about would be appreciated.
// I know using string concatenation for querys is bad
You have to do it the hard way: one query to get the count and another to get your desired slice of the row set:
my $count = $database->prepare('SELECT COUNT(*) FROM content');
$count->execute();
my $n = $count->fetchall_arrayref()->[0][0];
my $content = $database->prepare('SELECT * FROM content LIMIT ?');
$content->execute($CONTNUM);
#...
Not too familiar with perl, but I assume you can just store the result of $content->fetchall_arrayref and retrieve the count from that array befor you print it.
[edit]
Something like
my $ref = $content->fetchall_arrayref;
my $count = scalar(#$ref);
Don't use sqlite myself but the following might work:
select * from table join (select count(*) from table);
Whether the above works or not the first thing I'd look for is scrollable cursors if you are going to page through results - I doubt sqlite has those. However, in DBI you can use fetchall_arrayref with a max_rows to fetch a "page" at a time. Just look up the example in the DBI docs under fetchall_arrayref - it is something like this:
my $rowcache = [];
while( my $row = ( shift(#$rowcache) || shift(#{$rowcache=$sth->fetchall_arrayref(undef,100)||[]}) )
) {
# do something here
}
UPDATE: Added what you'd get with selectall_hashref assuming the table is called content with one integer column called "a":
$ perl -le 'use DBI; my $h = DBI->connect("dbi:SQLite:dbname=fred.db"); my $r = $h->selectall_hashref(q/select * from content join (select count(*) as count from content)/, "a");use Data::Dumper;print Dumper($r);'
$VAR1 = {
'1' => {
'count' => '3',
'a' => '1'
},
'3' => {
'count' => '3',
'a' => '3'
},
'2' => {
'count' => '3',
'a' => '2'
}
};
If you want to know how many results there will be, as well as getting the results themselves, all in one query, then get the count as a new value:
SELECT COUNT(*) AS num_rows, * from Table WHERE ...
Now the row count will be the first column of every row of your resultset, so simply pop that off before presenting the data.