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

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,

Related

Get latest Tweets - What API

I know this has been discussed a lot here, but I still don't seem able to find aworking solution. Either it's out of date, it's the wrong programming-language or it's no longer supported.
All I want to do is: Get the last 'n' tweets from a public Twitter profile using PHP/JavaScript.
What API should I use best?
How do I keep it as lightweight as possible?
I can't use Node. js
I tried this, but I can't seem to get it to work, as simple as it may look like.
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
I've already registered for a developer account and created a "Twitter-App".
You can use this API, which I have used once and it works perfectly.
Download the file TwitterApiExchange.php from the repository above and you may use the following sample code to fetch tweets of a user:
<?php
echo '<pre>';
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$user = "rootcss";
$count = 100;
if (isset($_GET['user'])) {
$user = $_GET['user'];
}
if (isset($_GET['count'])) {
$count = $_GET['count'];
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest(), $assoc = TRUE);
if (isset($string["errors"][0]["message"])) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>" . $string['errors'][0]["message"] . "</em></p>";
exit();
}
foreach ($string as $items) {
echo "Time and Date of Tweet: " . $items['created_at'] . "<br />";
echo "Tweet: " . $items['text'] . "<br />";
echo "Tweeted by: " . $items['user']['name'] . "<br />";
echo "Screen name: " . $items['user']['screen_name'] . "<br />";
echo "Followers: " . $items['user']['followers_count'] . "<br />";
echo "Friends: " . $items['user']['friends_count'] . "<br />";
echo "Listed: " . $items['user']['listed_count'] . "<br /><hr />";
}
echo '</pre>';
?>
It worked perfectly for me, Let me know if you face any issues.

Instagram API pagination in PHP

I am trying to create a small instagram app in PHP only (no database) and without getting an access_token (just my client_id). So far so good, (i.e. input user_id returns photos from last 30 days, with likes-count and created_time, in a table), until I get to pagination. As expected, I want to hit a 'more' button which loads next json file and adds additional photos to the existing table, but it falls apart there... Here is what I've got, working, except for the pagination attempt.
NOTE: this is an internal app, so the sensitivity of my client_id is not an issue, if it is exposed
<?php
if (!empty($_GET['user_id'])){
$user_id = ($_GET['user_id']);
$instagram_url = 'https://api.instagram.com/v1/users/' . $user_id . '/media/recent/?client_id=MY_CLIENT_ID';
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json, true);
}
?>
...
<?php
if(!empty($instagram_array)){
$instagram_array['pagination'] as $page { // Attempt at pagination
echo '<p>' .$page['next_url'].'</p>'; // Attempt at pagination
} // Attempt at pagination
foreach($instagram_array['data'] as $image){
if ($image['created_time'] > strtotime('-30 days')) {
echo '<tr>';
echo '<td>' . date('M d, Y', $image['created_time']) . '</td>';
echo '<td>'.$image['likes']['count'].'</td>';
echo '<td><img src="'.$image['images']['standard_resolution']['url'].'" alt=""/ style="max-height:40px"></td>';
echo '</tr>';
}
}
}
?>
</body>
</html>
Note: this is cobbled together from a few other sources - I am a total noob, so please forgive me if I need a little hand-holding...:)
You may specify min_timestamp to return medias which taken later than this timestamp
https://api.instagram.com/v1/users/{user_id}/media/recent/?access_token={access_token}&min_timestamp={min_timestamp}
$instagram_array['pagination']['next_url'] should be removed, it may include your access token which is a sensible data, that must be always invisible.
list_ig.php
<?
$user_id = "...";
$access_token = "...";
//30 day ago
$min_timestamp = strtotime("-30 day",time());
//pagination feature
$next_max_id = $_GET['next_max_id'];
$instagram_url = "https://api.instagram.com/v1/users/" . $user_id . "/media/recent/?access_token=" .$access_token. "&min_timestamp=" . $min_timestamp;
if($next_max_id != "")
$instagram_url .= "&max_id=" . $next_max_id;
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json ,true);
?>
<? if( $instagram_array['pagination']['next_max_id'] != "" ): ?>
More
<? endif;?>
.... print instagram data....
Instagram AJAX Demo
http://jsfiddle.net/ajhtLgzc/

How to get a value from wunderground .json

I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632

How to use Caching Feature of PHP last.fm API

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>";
?>

PHP looped data will not echo outside the while function OR how can I pass looped data by echoing out of the while function?

I have a loop of data that will only echo the loop inside the while function, but if i call/echo the looped data outside the while function, it only runs the 1st loop.
SAMPLE:
$num = mysql_num_rows($queryFromDB);
$i=0;
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$i++;
// This will only show 1 row of data. How can I pass the looped data to another variable?
echo $bothFields;
}
The output that I wanted to show is:
TITLE/HEADER GOES HERE in the 1st Line
-1st Row of Data from DB
-2nd Row of Data from DB
Here's the actual code:
$num = mysql_num_rows($qWoundAssessment);
$i=0;
while ($i < $num)
{
$wndType = mysql_result($qWoundAssessment,$i,"wndType");
$wndNum = mysql_result($qWoundAssessment,$i,"wndNum");
$wndLocation = mysql_result($qWoundAssessment,$i,"wndLocation");
$wndStage = mysql_result($qWoundAssessment,$i,"wndStage");
$wndL = mysql_result($qWoundAssessment,$i,"wndL");
$wndD = mysql_result($qWoundAssessment,$i,"wndD");
$wndW = mysql_result($qWoundAssessment,$i,"wndW");
$wndAseptic = mysql_result($qWoundAssessment,$i,"wndAseptic");
$wndIrrigate = mysql_result($qWoundAssessment,$i,"wndIrrigate");
$wndIrrigateBox = mysql_result($qWoundAssessment,$i,"wndIrrigateBox");
$wndPat = mysql_result($qWoundAssessment,$i,"wndPat");
$wndCover = mysql_result($qWoundAssessment,$i,"wndCover");
$wndCoverBox = mysql_result($qWoundAssessment,$i,"wndCoverBox");
$wndSecure = mysql_result($qWoundAssessment,$i,"wndSecure");
$wndSecureBox = mysql_result($qWoundAssessment,$i,"wndSecureBox");
$wndQvisit = mysql_result($qWoundAssessment,$i,"wndQvisit");
$wnd = "-" . $wndType . " " . "#" . $wndNum . ", " . "LOCATION " . $wndLocation . ", " . "STAGE " . $wndStage;
$wndSize = "SIZE " . $wndL . "CM" . " X " . $wndW . "CM" . " X " . $wndD;
if($wndAseptic=="1"){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if($wndIrrigate=="1"){$wndIrrigateWith = "IRRIGATE WITH " . $wndIrrigateBox;}
if($wndPat=="1"){$wndPatDry = "PAT DRY";}
if($wndCover=="1"){$wndCoverWith = "COVER WITH " . $wndCoverBox;}
if($wndSecure=="1"){$wndSecureWith = "COVER WITH " . $wndSecureBox;}
if($wndQvisit=="1"){$wndQv = "Q VISIT";}
if(isset($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)){
$woundCare = implode(", ",array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)) . "\n\n ";}
$wndCare .= $woundCare;
$i++;
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
if I echo $wndCare, it shows the "Undefined variable" error with the actual looped data. But if I pass this variable to PDF, it works.
SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:
-PRESSURE ULCER #1, LOCATION COCCYX, 3, SIZE 2.0CM X 1.5CM X 0.07, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
-SURGICAL WOUND #2, LOCATION (R) KNEE, , SIZE 29CM X 0CM X 0, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
================ CODE NOW WORKS!!! HERE's MY FINAL SOLUTION ======================
$num = mysql_num_rows($qWoundAssessment);
$i=0;
$storeMyData = array();
while($i < $num)
{
$wnd= "-" . mysql_result($qWoundAssessment,$i,"wndType") . " #" . mysql_result($qWoundAssessment,$i,"wndNum"). ", LOCATION " . mysql_result($qWoundAssessment,$i,"wndLocation") . ", STAGE " . mysql_result($qWoundAssessment,$i,"wndStage");
$wndSize = "SIZE " . mysql_result($qWoundAssessment,$i,"wndL") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndW") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndD") . "CM";
if(isset($rowWoundAssessment['wndAseptic'])){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if(isset($rowWoundAssessment['wndIrrigate'])){$wndIrrigateWith = "IRRIGATE WITH " . mysql_result($qWoundAssessment,$i,"wndIrrigateBox");}
if(isset($rowWoundAssessment['wndPat'])){$wndPatDry = "PAT DRY";}
if(isset($rowWoundAssessment['wndCover'])){$wndCoverWith = "COVER WITH " . mysql_result($qWoundAssessment,$i,"wndCoverBox");}
if(isset($rowWoundAssessment['wndSecure'])){$wndSecureWith = "SECURE WITH " . mysql_result($qWoundAssessment,$i,"wndSecureBox");}
if(isset($rowWoundAssessment['wndQvisit'])){$wndQvisit = "Q VISIT";}
$wndCare = implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQvisit)). "\n\n";
// This will show 2 rows of data
$storeMyData[] = $wndCare ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
/* or join the data using string concatenation /
$allFinalData2 = "";
/ this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $allFinalData2;
thanks to DhruvPathak and Antonio Laguna! You guys are the best! Just made my day! jumps around the room
This should work:
<?php
$wndCare = '';
while ($row = mysql_fetch_assoc($qWoundAssessment)){
$wnd = '-'.$row['wndType'].' #'..$row['wndNum'].', LOCATION '.$row['wndLocation'].', STAGE '.$row['wndStage'];
$wndSize = 'SIZE '.$row['wndL'].'CM X '.$row['wndW'].'CM X '.$row['wndD'];
$wndAsepticTech = ($row['wndAseptic'] == 1) ? 'USING ASEPTIC TECHNIQUE' : '';
$wndIrrigateWith = ($row['wndIrrigate'] == 1) ? 'IRRIGATE WITH '.$row['wndIrrigateBox'] : '';
$wndPatDry = ($row['wndPat'] == 1) ? 'PAT DRY' : '';
$wndCoverWith = ($row['wndCover'] == 1) ? 'COVER WITH'.$row['wndCoverBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndQvisit = ($row['wndQvisit'] == 1) ? 'Q VISIT' : '';
$wndCare .= implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)). '\n\n';
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
?>
The issue I see is that you were testing if all variables where previously setted and this could make strange things as you were stablishing them sometimes and sometimes don't.
I am not sure what you want to do with your data. It seems you want to store
all the data to use it outside the loop, then this is the way to go :
<?php
$num = mysql_num_rows($queryFromDB);
$i=0;
$storeMyData = array();
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$storeMyData[] = $bothFields ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
echo $prevData."\n";
}
?>
$allFinalData = implode("",$prevData); // implode will join all the data as string
echo $allFinalData."\n" ;
/* or join the data using string concatenation */
$allFinalData2 = "";
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo $allFinalData2,"\n";
?>

Categories