Facebook user table fql to json_encode - php

I am using user table from fql.I am passing array to json_encode(). Facebook json format is not corrct, it is excluding []. How do I add this in my code.
Below code is a example but I do not under stand that code.
user table https://developers.facebook.com/docs/reference/fql/user
I want name,uid.
//to get album cover
$fql2 = "select src from photo where pid = '" . $values['cover_pid'] . "'";
$param2 = array(
'method' => 'fql.query',
'query' => $fql2,
'callback' => ''
);
$fqlResult2 = $facebook->api($param2);
$jsarr = array();
foreach( $fqlResult2 as $keys2 => $values2){
}
if ($values['name'] != 'Profile Pictures'){
$jsarr['src'] = $album['src'];
$count += 1;
if ($count == 1){
$outputStr .= "[";}
else {
$outputStr .= ",";}
$outputStr .= json_encode($values2);
}
}
$outputStr .= "]";
$outputStr = str_replace("{","[",$outputStr);
$outputStr = str_replace("}","]",$outputStr);
echo $outputStr;
}
?>

When you use the Facebook PHP SDK, it automatically decodes the returned json object into a PHP array. If you need a json object from it, you'll have to use json_encode on it after you finish processing it.
You've got some major problems with your php code. Just to get started:
Your foreach loop ends as soon as it starts with the } on the next line.
Where do you define the variables $values and $album?
You are referencing $values2 outside of your foreach loop.
You are appending to an uninitialized variable on your line $outputStr .= "[";.
If you pass json_encode() a proper php array of data, it will make a complete json object. You shouldn't need to be appending brackets of any kind.

Related

json_decode showing no data

I'm using below logic to store data in JSON format in MySQL using PHP.
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
session_start();
$date = new Date();
$modified = $date->getDate();
$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';
Then while decoding the data i'm using below logic:
$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$var = html_entity_decode($row['data']);
echo json_decode($var);
}
}
While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output
{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}
I'm not sure where i'm going wrong, could anybody help me out here?
I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so
echo json_encode(
array(
"type" => "error",
"status" => "Error While Retrieving Data!",
"message" => $error
)
);
I think you need something like:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[] = array($value[1] => $value[2]);
else
$store[] = array($value[1] => trim($value[2]));
}
$save = json_encode($store);
or even (if your $value[1] is always unique within the loop)
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
$save = json_encode($store);
then use $save to store in your table. I'm not 100% on that, though.
The string you've shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.
Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:
$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$storedata[] = array($value[1] => $value[2]);
else
$storedata[] = array($value[1] => trim($value[2]));
}
$jsondata = json_encode($storedata);
And then use $jsondata in your SQL statement.
Your problem is your "saving" to the database. You encode every key-value-pair in an own json-string and concat those json-strings.
Your snippet
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.
However, I assume you want a single json-object with the key-value-pairs as result like the folling?
$store = "{
key1:value1,
key2:value2,
key3:value3
}";
If so, you need to build your array differently:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.

Undefined Variable - PHP Code Snippet In Wordpress

I know this has been answered many times, but I don't know why I'm getting this error:
Notice: Undefined variable: urlfilter in
/home/mjburkel/public_html/allxxcars/wp-content/plugins/insert-php/includes/shortcodes/shortcode-php.php(52)
: eval()'d code on line 75
I know that this would normally be if the variable is not defined yet, but I am declaring it, thus I'm not exactly sure what the issue is. here is my code..note this is php code that I'm inserting into a Wordpress PHP snippet plugin...so, not sure if that plugin is inserting some weird code or not reading it properly maybe?
<?php /* Template Name: Completed W517 */
error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = 'XXX'; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = 'ford mustang'; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
// Create a PHP array of the item filters you want to use in your request
$filterarray =
array(
array(
'name' => 'MaxPrice',
'value' => '1000000',
'paramName' => 'Currency',
'paramValue' => 'USD'),
array(
'name' => 'MinPrice',
'value' => '100',
'paramName' => 'Currency',
'paramValue' => 'USD'),
array(
'name' => 'SoldItemsOnly',
'value' => 'true'),
);
function CurrencyFormat($number)
{
$decimalplaces = 2;
$decimalcharacter = '.';
$thousandseparater = ',';
return number_format($number,$decimalplaces,$decimalcharacter,$thousandseparater);
}
// Generates an indexed URL snippet from the array of item filters
function buildURLArray ($filterarray) {
global $urlfilter="";
global $i="";
// Iterate through each filter in the array
foreach($filterarray as $itemfilter) {
// Iterate through each key in the filter
foreach ($itemfilter as $key =>$value) {
if(is_array($value)) {
foreach($value as $j => $content) { // Index the key for each value
$urlfilter .= "&itemFilter($i).$key($j)=$content";
}
}
else {
if($value != "") {
$urlfilter .= "&itemFilter($i).$key=$value";
}
}
}
$i++;
}
return "$urlfilter";
} // End of buildURLArray function
// Build the indexed item filter URL snippet
buildURLArray($filterarray);
// Construct the findItemsByKeywords HTTP GET call
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findCompletedItems";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&categoryId=213";
$apicall .= "&paginationInput.entriesPerPage=20";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
if ($item->pictureURLLarge) {
$pic = $item->pictureURLLarge;
} else {
$pic = $item->galleryURL;
}
$link = $item->viewItemURL;
$title = $item->title;
$price = $item->sellingStatus->convertedCurrentPrice;
$bids = $item->sellingStatus->bidCount;
$end = $item->listingInfo->endTime;
$fixed = date('M-d-Y', strtotime($end));
if(empty($bids)){
$bids = 0;
}
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div class=\"item\"><div class=\"ui small image\"><img height=\"200px\" width=\"130px\" src=\"$pic\"></div><div class=\"content\"><div class=\"header\">$title</div><div class=\"meta\" style=\"margin-top:.1em\"><span class=\"price\"></span><div class=\"extra\">Sold Date: $fixed</div><div class=\"extra\"><button class=\"ui button\"><b>Number of Bids:</b> $bids </button></div><div class=\"extra\"><button class=\"ui orange button\">Sold Price: $$price</button></div><div class=\"description\"></div></div></div></div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h3>";
}
?>
What version of PHP are you using? You should actually be getting a syntax error when you first declare $urlfilter in your buildURLArray() function:
php: error - unexpected '=', expecting ',' or ';' in Standard input code
Because you're not supposed to be defining a variable after invoking it with the global keyword.
Basically, you should replace the beginning of your function with this:
// Generates an indexed URL snippet from the array of item filters
function buildURLArray ($filterarray) {
global $urlfilter, $i; // Load global variables
//…
}
And $urlfilter should be defined in the global scope, not the function scope. You could probably just put it under $i = '0'; // Initialize the item filter index to 0

Count and print values of HTTP API

Looking for help in counting all values that are present in HTTP API. The link below outputs the values of multiple data points by date. What I am trying to achieve is a count on each value so that instead of
a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;}
I want to output the above nb_pageviews as a key with the value of the dates combined - 2056.
Example Link for API is https://demo.piwik.org/?module=API&method=Actions.get&idSite=7&period=day&date=last2&format=php&token_auth=anonymous
And the PHP to display this is
$url = "https://demo.piwik.org/";
$url .= "?module=API&method=Actions.get";
$url .= "&idSite=7&period=day&date=last2";
$url .= "&format=php";
$url .= "&token_auth=anonymous";
$fetched = file_get_contents($url);
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
foreach ($content as $row) {
$pageviews = $row['nb_pageviews'];
print("<div>$pageviews</div>\n");
}
Please note that the above link contains multiple other values that I will be wanting to do the same with, yet for ensuring the readability of this question I have kept the values simple and to just the one.
Just use the combined assignment operator, and be sure to set defaults of 0, before the loop.
$fetched = 'a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;s:17:"nb_uniq_pageviews";d:964;s:12:"nb_downloads";d:2;s:17:"nb_uniq_downloads";d:2;s:11:"nb_outlinks";d:68;s:16:"nb_uniq_outlinks";d:64;s:11:"nb_searches";d:33;s:11:"nb_keywords";d:16;s:19:"avg_time_generation";d:0.78600000000000003;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;s:17:"nb_uniq_pageviews";d:10;s:12:"nb_downloads";i:0;s:17:"nb_uniq_downloads";i:0;s:11:"nb_outlinks";d:1;s:16:"nb_uniq_outlinks";d:1;s:11:"nb_searches";d:2;s:11:"nb_keywords";d:2;s:19:"avg_time_generation";d:0.79300000000000004;}}';
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
$pageviews = 0;
$uniq_pageviews = 0;
// and on, with your other vars you're looking to sum...
foreach ($content as $row) {
$pageviews += $row['nb_pageviews'];
$uniq_pageviews += $row['nb_uniq_pageviews'];
}
var_export(['pageviews' => $pageviews, 'uniq_pageviews' => $uniq_pageviews]);
Working demo: https://eval.in/930183
// Output
array (
'pageviews' => 2056.0,
'uniq_pageviews' => 974.0,
)
To print these values, you might replace the var_export line with something like this:
$data = [
'pageviews' => $pageviews,
'uniq_pageviews' => $uniq_pageviews
];
Which you could output in some HTML like so:
<div class="col-md-4"><?php echo $data['pageviews']; ?></div>
<div class="col-md-4"><?php echo $data['uniq_pageviews']; ?></div>

change array values during foreach. Adding html element to every array item

I wanted to ask, how can i modify array values when doing foreach - in my example, i want to add to every element, but this code produces error.
foreach ($logo as &$value) {
$value = '<div>' . $value . '</div>';
debug ($value);
}
?>
and the error: Notice (8): Array to string conversion
I'm using php 5.6
Thanks for reply.
I use
$serviceMe = ""; //OR use beginning html
foreach( $tmp as $t ) $serviceMe .= '<tr>' . $t . '</tr>';
$serviceMe .= ""; // Rest of the needed html
Make absolutely sure what type of is your $value. Is it integer,float,string,object,array... etc
I think your error comes from trying to convert array to string without proper handling.
$array = new array(
'key' => $value,
'key2' => $value2,
'key3' => $value3,
);
$string = "" . $array; //throws error!

Need help with PHP homework - friend matching algorithm

I'm totally new to php and have started learning it. I have two homework assignments in php and html.
Assignment 1:
I have to store some people's names and all of their friends names. I have to list only people who have common friends. My problem is that if a person has no friends in common with someone else I get a message "Rana has 0 friends in common with Roni. I do I prevent this:
Assignment 2:
I have a html form to search for a person from the last php file
When I will search for Rana the PHP form will open and and print:
Rana have 4 friends and he has a common friend with Nandini and Mamun.
When I search for Tanmoy the page will be open and print:
Tanmoy is Rana’s friend who has 4 friends and common friends with Nandini and Mamun.
For this I have to used the function “post/get/request”
Here is my code so far:
<?php
# Function: finfCommon
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
$final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
# Array of users and friends
$Friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
# Creating the output value
$output = "<ul>";
foreach ($Friends As $user => $friends) {
$total = count($friends);
$common = findCommon($user, $Friends);
$output .= "<li><u>{$user} has {$total} friends.</u><br /><strong>Friends:</strong>";
if (is_array($friends) && !empty($friends[0])) {
$output .= "<ul>";
foreach ($friends As $friend) {
$output .= "<li>{$friend}</li>";
}
$output .= "</ul>";
}
$output .= "{$common}<br /><br /></li>";
}
$output .= "</ul>";
# Printing the output value
print $output;
?>
For the assignment 1.1: You have just to filter out the unwantend responses with an
if ($total>0) {
$output .= "<li><u>{$user} has {$ ...
}
clause.
For the second assignment:
You have to create a page that expects a parameter to be read via $_GET or $_POST or $_REQUEST (call it name, for example). They are not functions, are arrays and you can access them from every scope in you program (they are superglobals and you don't need to declare them with gobals).
I would just print a select with the known people if the name (eg. $_REQUEST['name'] )is missing just print the form, otherwise find the person indicated by the input and print the result of the search.
EDIT:
For the second assignment, you will have to figure how to get the input data.
Probably I will use an approach a bit different
Provided that you have a form similar to this
<form action="homework.php" method="get">
Person: <select name="searchperson" />
<option> </option>
...
<option> </option>
</select>
</form>
you will have to get the list of all the known peoples in a manner similar to this:
$friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
// create a flat array with all the known peoples
$knownPeople = array_reduce(
$friends,
function($current, $result) {
return array_merge($result, $current);
},
array_keys($friends)
);
$knownPeople = array_flip(array_flip($knownPeople)); //get rid of duplicates
asort(knownPeople); // sort the names
$knownPeople = array_values($knownPeople); // normalize the array indexes
and then get the form you need with a function like this:
function theForm($people) {
$options = '<option>'.join("</option>\n<option>",$people). '</option>';
echo "
<form action=\"homework.php\" method=\"get\">
<h2>Chose the people you want investigate on:</h2>
Person: <select name=\"person\" />
$options
</select>
</form>";
}
Whenever you get a grasp on the previous code or not, you have to evaluate the input and take the opportune actions:
Let say that your script is called homework.php (you will see the name into the action of the form) and it is located ad http://example.com. His URI will be http://example.com/homework.php
There are several possible scenarios:
the user call the script for the first time
the user choose a person from the select
the user invoke your script manually with a known person as parameter
the user invoke your script manually with a person you don't have in your list
Let's review the different cases:
the user call the script for the first time
What appened: the user go to http://example.com/homework.php crossing a link or writing the URI into the browser address bar.
How you detect this scenario: Given the form above you can check $_GET['person']. if it is not isset or empty or not array_key_exists you can state you are into the first scenario.
To do: Just output the form and exit.
the user choose a person from the select
What appened: the user get the form (first scenario) and choose a name from the select.
How you detect this scenario: The detection of the first scenario fails and you can find the name contained into $_GET['person'] into the knownPeople array.
To do:
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
apply your functions to the person in input in order to get the desired output
output the result you got
the form for a new query or a link to http://example.com/homework.php
the user invoke your script manually with a known person as parameter
What appened: the user use a URI like http://example.com/homework.php?person=Rana to reach the script
How you detect this scenario: If the method you use in the form is get you can't (at least not using this simple scenarion) and you won't bother to as it can be considered a legal request as this is an homework and you don't have requirements about it. If you used the method post you have the chance to detect the forgeries as the parameter passed with that method are usually stored into the $_POST array. You can still find the name contained into $_GET['person'] into the knownPeople array.
To do: Same as second scenario
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
apply your functions to the person in input in order to get the desired output
output the result you got
the form for a new query or a link to http://example.com/homework.php
the user invoke your script manually with a person you don't have in your list
How you detect this scenario: The detection of the first scenario fails and you can not find the name contained into $_GET['person'] into the knownPeople array.
To do:
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
as the check fails output an error messages stating the user is unknown and let the user go to the correct uri with a link to http://example.com/homework.php.
Not all forgeries are bad. Consider an user that make a legal search and bookmark the result. If the list of friends change and then he returns to the page using the bookmark. He will fall straight into the fourth scenario
Hope this will help you to comprehend how the php scripting works.
change findCommon function from
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
$final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
to
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
if ( $total > 0 ) $final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
The change is i added a if ( $total > 0 ) before $final[] = ..
for the second one.
<?php
function searchPerson($person, $friends){
$direct = false;
$found = false;
if ( in_array ($person, array_keys($friends) ) ){
list($total, $common_friends) = commonFriend ($person, $friends);
$direct = true;
$found = true;
}
else{
foreach ( $friends as $friend => $his_friends ){
if ( in_array ( $person, $his_friends ) ){
list($total, $common_friends) = commonFriend ($friend, $friends);
$direct = false;
$found = true;
$friend_person = $friend;
break;
}
}
}
if ( !$found ) return false;
$output = $person . " ";
if ( $direct ){
$output .= " has " . $total . " friends";
}
else{
$output .= " is " . $friend_person . "'s friend who has " . $total . " friends";
}
if ( isset($common_friends[0]) ) $output .= " and common friends with " . $common_friends;
return $output;
}
function commonFriend ($person, $friends){
$my_friends = $friends[$person];
unset($friends[$person]);
$total_friends = count($my_friends);
$common_with = array();
foreach ( $friends as $friend => $his_friends ){
foreach ( $my_friends as $my_friend ){
if ( in_array ($my_friend, $his_friends) ){
$common_with[] = $friend;
}
}
}
$common_with = array_unique ($common_with);
$common_friends = "";
if ( count($common_with) > 0 ){
$common_friends = join (", ", $common_with );
}
return array ( $total_friends, $common_friends );
}
$friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
$person = $_GET['person'];
$output = searchPerson($person, $friends);
if ( $output === false ) print $person . " is not on the list";
else print $output;
?>
What you have to do with the second assignment is you need a form.
lets say the above code was named searchPerson.php
then add a html page like
<html>
<head>
<title>Search for friend</title>
</head>
<body>
<form action="searchPerson.php" method="get">
Person: <input type="text" name="person" /><input type="submit" value="search" />
</form>
</body>
</html>
or run directly like
searchPerson.php?person=Rana
And why you get a message like that is because $person = $_GET['person']; gets the person name from the url, and u must have run it like searchPerson.php, so their is no value for $person to check.
-- EDIT
Chaged the code to work with people not in the list

Categories