How to use Caching Feature of PHP last.fm API - php

I'm using PHP last.fm API to fetch artist image
I'd like to know how to cache the calls so that I don't need to make same call again and again. The API has facility to cache : DiskCache, SqliteCache but there is no documentation, could anyone please shed some light on it?
Below is my code :
<?php
require __DIR__ . "/src/lastfm.api.php";
// set api key
CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);
// search for the Coldplay band
$artistName = "Coldplay";
$limit = 1;
$results = Artist::search($artistName, $limit);
echo "<ul>";
while ($artist = $results->current()) {
echo "<li><div>";
echo "Artist URL: " . $artist->getUrl() . "<br>";
echo '<img src="' . $artist->getImage(4) . '">';
echo "</div></li>";
$artist = $results->next();
}
echo "</ul>";
?>

Related

PHP is it possible to assign a variable to an "IF"

I am starting on PHP, and i need a little help, I have my php file ytpost.php with the following content:
EDIT: I have my code a little bit disorganized,
<?php
$yturl = $_POST['urlyt']; //gets a youtube url
$yturlhttp = str_replace("https","http",$yturl); //replaces HTTPS with http
$ytid = substr(strstr($yturlhttp, 'http://www.youtube.com/watch?v='), strlen('http://www.youtube.com/watch?v=')); //removes everything before the video ID
$apikey = "blabla"; //youtube api
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=$ytid&key=$apikey"); //using youtube api to get video info
$json_data = json_decode($JSON, true);
$getvideoviews = $json_data['items'][0]['statistics']['viewCount'];
$getvideolikes = $json_data['items'][0]['statistics']['likeCount'];
$getvideodislikes = $json_data['items'][0]['statistics']['dislikeCount'];
$getvideofavorites = $json_data['items'][0]['statistics']['favoriteCount'];
$getvideocomments = $json_data['items'][0]['statistics']['commentCount'];
$paloma = "✔"; //checkmark in spanish
$tacha = "✘"; //cross in spanish
$minimumvideoviews = "4000"; //minimum video views to be accepted
$minimumvideolikes = "100"; //minimum video likes to be accepted
//echo "views: " . $getvideoviews . "<br/>"; //TESTING
//echo "likes: " . $getvideolikes . "<br/>"; //TESTING
//echo "dislikes: " . $getvideodislikes . "<br/>"; //TESTING
//echo "favorites: " . $getvideofavorites . "<br/>"; //TESTING
//echo "comments: " . $getvideocomments . "<br/>"; //TESTING
if ($getvideoviews < $minimumvideoviews) {
echo "$tacha you dont have the minimum views to qualify for VIP ($minimumvideoviews minimum)<br/>";
}
else{
echo "$paloma you do have the minimum views to qualify for VIP ($minimumvideoviews minimum)<br/>";
};
if ($getvideolikes < $minimumvideolikes) {
echo "$tacha you dont have the minimum likes on your video to qualify for VIP ($minimumvideolikes minimum)<br/>";
}
else{
echo "$paloma you do have the minimum likes on your video to qualify for VIP ($minimumvideolikes minimo)<br/>";
};
?>
my problem is the following, i need to display something if both youtube views and youtube likes are exactly or over $minimumvideoviews and $minimumvideolikes, thank you.
, I dont have an idea on how to accomplish this,

php echo iframe or image

Hey everyone I am having an issue with echoing an image or an iframe, the idea is there is an image link or an iframe in the same row in the database & i want to only echo what the string content is, if it echos the iframe there is a blank space of an image & underneath is the youtube video, if it echos the image the iframe does not show, they both currently echo the same row id labled url, I only want one to echo based on the string content instead of both echo's.
Here is the code I use to fetch the stuff, its only the echo area you want to pay attention to, I am not sure what kind of, if or else statement i could put in here.
< ?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 4;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM bookmarks WHERE 1 ORDER BY id DESC LIMIT $limit OFFSET
$offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
echo '<img src=' . $row['url'] . '></br>'; /*here */
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
} }
?>
This script is a get results php
The best solution would be to save the data in different columns in the database. But if you want to keep the current structure would be able to check if the string contains HTML, then it is an iframe. Otherwise it is a link to the image.
<?php
if($row['url'] == strip_tags($row['url'])) {
//No HTML in string = link
echo '<img src="' . $row['url'] . '" alt="" />';
} else {
//Contains HTML = iframe
echo $row['url'];
}
?>
This assumes that you in your database have saved the values as either http://www.exempel.com or <iframe src =" http: // www ... ">. If the iframe-value also consists only of a URL, you must use another solution.
If you know whether the url is an image or video when you save them in the database then you could add another field for the media type. You could then use this in an if statement in your code, for example:
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
if ($row['mediaType'] === 'image') {
echo '<img src=' . $row['url'] . '></br>'; /*here */
} if ($row['mediaType'] === 'video') {
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
}
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
}
}

Using a function to query a database

I have a page and I would really like some help / advice to create a better way / function to call in information from another table.
At the moment, my code looks like:
[I do know this is deprecated SQL and would really like to do some nice SQLi for this.]
<?
$menuid = "100";
$imageid = "50";
// ** Talk to 'imagedirectory' table
mysql_select_db($database_db, $BASEdb);
$query_displayimage = "SELECT * FROM imagedirectory WHERE menuid = ".$menuid." AND imageid = ".$imageid."";
$displayimage = mysql_query($query_displayimage, $BASEdb) or die(mysql_error());
$row_displayimage= mysql_fetch_assoc($displayimage);
?>
<img src="/images/assets/<?php echo $menuid; ?>-<?php echo $imageid; ?>-<?php echo $row_displayimage['urlslug']; ?>.jpg" alt="<?php echo $row_displayimage['alttext']; ?>" />
I figure There really has to be a better way because if there is 10 images on a page, this is pretty intense way of doing it.
Since you seem to know that mysql_* is deprecated, I am assuming you have read up on, and are using mysqli_* instead.
You needn't query the database every time. mysqli_query() returns a mysqli_result, which you can iterate over, and read using functions like mysqli_fetch_assoc(). Here is one way of doing it:
<?php
// store your query in a variable.
$query_displayimage = "SELECT * FROM imagedirectory";
// query the database.
$displayimage = mysqli_query($query_displayimage, $BASEdb);
// check for errors.
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
// iterate over the returned resource.
while ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
?>
Hope that helped.
EDIT:
You can use this code in a function, too. For example:
<?php
function printImage($menuid, $imageid)
{
$query_displayimage = "SELECT * FROM imagedirectory";
$displayimage = mysqli_query($query_displayimage, $BASEdb);
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
if ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
else // if there is a problem getting the image
{
echo 'Error getting image.';
}
}
?>
and elsewhere in your HTML, you would do something like:
<div>
And here is an image!
<?php printImage(20, 50); ?>
</div>

Fetch Product Images with BigCommerce API

Long story short a couple months ago i made a plugin for WordPress with the Bigcommerce API to fetch products in the Widget Area.
Now I have updated the Single File "Bigcommerce.php" and now the Function getProductImages () is none existent. And I cant seem to find the new function to get the Product Images. Maybe its just to late and Im tired or just plain Blind.
Please let me know how to fetch now the image for a specific product.
See below for the old code used i reverted back to the Old "Bigcommerce.php" and it works again but would ratehr use the new way.
Bigcommerce::configure(array(
'store_url' => $store_url,
'username' => $username,
'api_key' => $api_key
));
Bigcommerce::setCipher('RC4-SHA');
Bigcommerce::verifyPeer(false);
$countProducts = 0;
$products = Bigcommerce::getProducts();
shuffle($products);
echo '<div class="BCStoreWidget">';
if (!$products) {
echo '<div class="BCerror">';
$error = Bigcommerce::getLastError();
echo $error->code;
echo $error->message;
echo '</div>';
} else {
foreach ($products as $product) {
$productImages = Bigcommerce::getProductImages($product->id);
echo '<h4>' . $product->name . '</h4>';
if ($productImages->image_file){
echo '<div class="pimage">';
echo '<img src="' . $store_url . '/product_images/' . $productImages->image_file . '">';
echo '</div>';
}
// echo '<p>' . substr($product->description,0,100) . ' ...</p>';
echo '<p>' . number_format($product->price, 2, '.', '') . ' USD</p>';
echo '<p> Buy Now </p>';
$countProducts++;
if ($countProducts == $max_show)
break;
}
}
echo '</div>';
Thank you all in Advance
You can get product images just by getting the "images" attribute of the product object. So, all you have to do is:
$productImages = $product->images;
You can also access images directly using the getCollection function:
Bigcommerce::getCollection('/products/'.$product_id.'/images/');

PHP Facebook FQL Multquery and dealing with foreach and variables

Alright, so I am trying to figure this out. Basically I have everything working well except for adding the cover photos to each of the DIVS. Basically I have 2 queries using FQL, and here is my code.
$query =
'{"query1":"SELECT aid, cover_pid, name, description FROM album WHERE owner=$fbowner",
"query2":"SELECT src FROM photo WHERE pid IN (SELECT cover_pid FROM #query1)"}';
$fqlResult = $facebook->api(array(
'method' => 'fql.multiquery',
'queries' => $query));
$fql = $fqlResult[0]['fql_result_set'];
$covers = $fqlResult[1]['fql_result_set'];
$the_count = count($fql);
$i = 0;
foreach($fql as $value) {
$album_cover = $value['src'];
echo "<div class='fb_block'>";
echo "<a href='" . $url . "?action=list_pics&aid=" . $value['aid'] . "&album_name=" . $value['name'] . "'>";
echo "<img src='{$covers[$i]['src']}' border='1'>";
echo "</a>";
echo "<h3>".$value['name']."</h3>";
echo "<p>".$value['description']."</p>";
echo "</div>";
$i++;
}
Now that works fine, but what if I put this in the mix, the cover photos are all off unless I make $i = 1.
$i = 0;
foreach($fql as $value) {
if($value['name'] != 'Wall Photos'){
$album_cover = $value['src'];
echo "<div class='fb_block'>";
echo "<a href='" . $url . "?action=list_pics&aid=" . $value['aid'] . "&album_name=" . $value['name'] . "'>";
echo "<img src='{$covers[$i]['src']}' border='1'>";
echo "</a>";
echo "<h3>".$value['name']."</h3>";
echo "<p>".$value['description']."</p>";
echo "</div>";
$i++;
}
}
and if I stick another foreach in the mix, it grabs all the cover photos and sticks them into each div. So what is the easiest solution to just go in order and grab the cover photo associated with the album node?
Thanks in advance!
I tried this, too. You can't rely on the indexes being consistent between these two queries.
To make it work, first modify query2 to also return pid, then replace this line in your code:
echo "<img src='{$covers[$i]['src']}' border='1'>";
with this:
foreach($covers as $cover) {
if ($value['cover_pid'] === $cover['pid']) {
echo "<img src='{$cover['src']}' border='1'>";
break;
}
}

Categories