Everything's working fine but I was unable to retrieve the total number of results from the site (faroo)..
<?php
if (isset($_GET['q']))
{
$q = $_GET['q'];
$p = $_GET['p'];
$page = file_get_contents('http://www.faroo.com/api?q=' . $q
. '&start=' . $p . '&l=en&key='.$myownkey.'&src=web&f=json');
// echo $page->{'count'}; //this too not working
$dat_array = json_decode($page, true);
echo $dat_array->{'count'}; //not woking.
}
?>
where am I going wrong?
json_decode($page, true);
The second parameter as "true" turns the data into an associative array rather than an object. To access the data this should work:
echo $dat_array['count'];
Related
I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}
I'm a beginner in php. I'm trying get a variable number from sql ,
I have this part of code:
function renderNotification()
{
if ($user_id = $this->getDi()->auth->getUserId()) {
$cnt = $this->getDi()->db->selectCell("SELECT COUNT(ticket_id) FROM ?_helpdesk_ticket WHERE status IN (?a) AND user_id=?",
array(HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE), $user_id);
if ($cnt)
return '<div class="am-info">' . ___('You have %s%d ticket(s)%s that require your attention',
sprintf('', REL_ROOT_URL . '/helpdesk/index/p/index/index?&_user_filter_s[]=awaiting_user_response'), $cnt, '') .
'</div>';
}
}
i want get number of ticket only in other place in my program
This is my try:
<?php echo "%s%d" ; ?>
or
<?php echo $cnt ; ?>
but not work
i'm using Zend , sf , pear , all what i need output %s%d ticket(s)%s from above code in other place or call it
i have found correct way it's below
<?php
$cnt = $di->db->selectCell("SELECT COUNT(ticket_id)
FROM ?_helpdesk_ticket
WHERE status IN (?a)
AND user_id=?",
array(HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE),
$di->user->pk());
echo $cnt;
?>
I am designing a php application using AJAX and PHP.
But the if statement in my php file behaves unexpectedly.
The request method is 'POST';
Ajax code is
function fetchData(){
var recipename = document.getElementById("recipe").value;
var calorie = false;
createRequestObject();
//window.alert(calorie);
var url = "reciepinfo.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.alert(calorie);
xmlHttp.send("recipe="+recipename+"&calorie="+calorie);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState===4 && xmlHttp.status===200){
document.getElementById("target").innerHTML = xmlHttp.responseText;
}
}
}
And php code is:
<?php
$_SESSION['flag']=false;
if($_SESSION['flag']==false){
session_start();
$_SESSION['flag']=true;
}
$recipename = $_REQUEST['recipe'];
$calorie = $_REQUEST['calorie'];
echo $calorie;
$calorietemp = 0;
//echo $recipename;
$database = "nutrition";
$link = mysqli_connect('localhost','root','',$database);
$query = "select * from recipestb where name='$recipename'";
//$result = mysqli_query($link,$query);
//$obj = mysqli_fetch_object($result);;
if($link){
$result = mysqli_query($link,$query);
$obj = mysqli_fetch_object($result);
//$arr = mysqli_fetch_array($result);
//$names = "";
if(is_object($obj)){
echo "<i/>";
echo "<font size='5'>";
echo "Recipe name: ".$obj->name;
echo '<br/>';
echo "Carbohydrates : ".$obj->carbs." grams";
echo '<br/>';
echo "Proteins: ".$obj->protein." grams";
echo '<br/>';
echo "Fat: ".$obj->fat." grams";
echo '<br/>';
echo "Calories: ".$obj->calorie." cal";
$calorietemp = $obj->calorie;
echo '<br/>';
}else{
echo "non object";
}
}else{
echo "Connection failed";
}
if($calorie==true){
echo $calorie;
$_SESSION['caloriecount'] = $_SESSION['caloriecount'] + $calorietemp;
echo "Total calorie in diet :".$_SESSION['caloriecount'];
}
My session handling is weird i accept, but neglecting that, even the variable calorie is explicitly set to false, the if block executes.The echo $calorie statement also executes and it displays $calorie as false.
And i am not getting what is going wrong exactly.
Almost irritated with this.
Can anybody help?
EDIT1:
The php code is fine...
Ajax code has some problem...
When i set the $calorie to false in php code..
It behaved properly..
Leaving the session handling aside, the $calorie problem ...
You pass the data via AJAX as strings.
$calorie = 'false';
var_dump((true == $calorie));
You will get always bool(true). Using your AJAX example above, try this snippet instead (and use POST instead of REQUEST):
$calorie = ('true' == $_POST['calorie']);
var_dump($calorie);
// produces `bool(false)`
As a beginner i was unaware that the java-script variable with value false is passed as a string "false" to a server side script like PHP.
If we use a boolval(), in PHP this issue can be resolved.
PHP boolval()
I set the $calorie in my java-script to 0 or 1 as per my need.
When i wanted the false value to be sent to PHP script ,i set $calorie in java-script to 0 and the boolval() in corresponding PHP script evaluated it as false.
So the issue was resolved.
I've got this url: /admin.php?op=admin&action=delete&link=/showitems.php?id=8745
I need to get the op parameter and the action and the link parameters as well. If I code something like this:
$op = $_GET['op'];
echo $op; //the output is admin
$action = $_GET['action'];
echo $action; //The output is nothing;
$link = $_GET['link'];
echo $link; //The output is nothing;
//IF I want to sanitize the data same happens with
$op = filter_input(INPUT_GET,"op",FILTER_SANITIZE_STRING);
echo $op; //the output is admin
$action = filter_input(INPUT_GET,"action",FILTER_SANITIZE_STRING);
echo $action; //the output is nothing
$link = filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);
echo $link; //the output is nothing
//If I go for the whole array of parameters there they are.
foreach($_GET as $key=>$value){
echo $key . " : " . $value; //The output is op : admin;action : deleteamp;link : /showitems.php?id=8745
}
what could it be the problem when I try to directly get the second or the third parameter like in this case action and link? Thanks for any advise. Greetings.
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/