Json response only current data - php

This is my query and all thing going very well. problem is that only json response. when I print json .its showing only one data .while I want to list all data of current user .so please if any help then let me know Thanks .
$user1 = $wpdb->get_results(
"select product,checked_by,submit_date from diary_user_form_storage where DATE(submit_date) = CURDATE() ;
");
foreach ($user1 as $key => $value) {
$productString = stripslashes($value->product);
$checked = stripslashes($value->checked_by);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$date=$value->submit_date;
$date1 = date('Y-m-d',strtotime($date));
$timing= date('H:i:s',strtotime($date));
$jsonString = "";
}
header('Content-type: text/json');
echo json_encode(
array(
"status" => "1",
'user_id' => $user->ID,
'message' => 'fetched',
"token" => $token,
'token' => $token.$device_id.$device_type,
'serverUrl' => $serverUrl,
'option'=>$option,
'product' => $product,
'checked_by' =>$checked_by ,
'submit_date'=>$timing
));
?>

You misunderstand what a foreach loop is, and may be confused about variable scoping. Each time the loop loops over an element of your query, this line is executed:
$productString = stripslashes($value->product);
which overwrites the same variable over and over again. So, in the end, when you echo json_encode(/*stuff*/) only the content of the last iteration of the loop gets outputted.
Luckily for you, you can just put the echo in the loop, and each part will be outputted by your script.
Make sure to put the header before that, or your script will fail. Headers (header('Content-type: text/json');) need to be sent before actual content.

Related

facebook pagination using next() URL error

I am working on facebook pagination, I have searched but didn't get relevant answer.
First I am fetching 10 result and after that onclick function I want to fetch next 10 results for this I am passing -
[paging] =>
Array
(
[previous] => https://graph.facebook.com/v2.9/....D&__previous=1
[next] => https://graph.facebook.com/........
)
as parameter,I also tried passing next URL as parameter but still it is not working, if I pass $feedEdge as associated I am getting response as null,below is my code
$response = self::$_FBINSTANCE->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
if(empty($_nextFeed)){
$feedEdge = $response->getGraphEdge();
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
$feedEdge=$response->next($_nextFeed);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
$result = array();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
using v2.9 version, what parameter I should pass for $response->next(); help me if I am wrong .
I found solution for this question...
If any one is trying for same try below code.
$result = array();
if(empty($_nextFeed)){
$response = $fb->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
//to get until time stamp form next url
$nextURl=parse_url($_nextFeed['paging']['next']);
parse_str($nextURl['query'], $URL);
$response = $fb->get('/me/feed?fields=id,message&limit='.(($_pagination->limit)+1).'&until='.$URL['until']);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
//because result repeats last array of previous request
array_splice($result,0,1);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
It works :)

php file that returns a string json encode didnt work

I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );

When using preg_replace on a variable in an array, the variable doesn't reflect preg_replace changes

I can't figure out what in the world is going wrong with my code.
Problem:
I'm getting results from a mysql DB, one of the variables returned needs to be run through preg_replace, the preg_replace() works just fine when I echo it out, but when I try to put that variable into the array, it doesn't reflect the preg_replace() changes.
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
So again, if I echo the $newdesc variable before the array code, it displays properly, but when the array is echo'd out at the end of the script, it doesn't.
Edit:
Someone requested the echo response, if I echo out $newdesc this string:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
simply echos out as this:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
And the code now reflects this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
echo $newdesc;
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
Edit again:
See answer for solution!
Thanks to the wonderful people in the comments, the solution to the problem was simply to use strip_tags() this my friends is a fine case of me being an idiot. Code is now this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
$newdesc = strip_tags($row['Desc']);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
And it works perfectly.
I was making a function that already existed, read the documentation on strip_tags() for more info.
http://php.net/manual/es/function.strip-tags.php

Controlling the output of a json feed

I'm trying to pull out a json feed from a Wordpress query. I need the JSON to be formatted [{"id":"1","title":"title"},{"id":"2","title":"title2"}]
The json_encode function is not pulling out this specific format: Items are not separated by commas and I'm also missing the initial and final [ ]
I made this code echoing those missing elements, which works good, but the final comma, because of the echo is making the script reading it to fail.
<?php
$args = array(
'post_type' => 'location',
'posts_per_page' => -1
);
$locations = new WP_Query($args);
if($locations -> have_posts()):
echo '[';
while ($locations->have_posts()) : $locations->the_post();
$coords = get_field('coordinates');
$pid = get_the_ID();
$json["id"] = $pid;
$json["name"] = get_the_title();
$json["lat"] = $coords['lat'];
$json["lng"] = $coords['lng'];
$json["address"] = get_field('address');
$json["address2"] = get_field('address_2');
$json["city"] = get_field('city');
$json["state"] = get_field('state');
$json["postal"] = get_field('zip_code');
$json["phone"] = get_field('office_phone');
$json["fax"] = get_field('office_fax');
$json["web"] = apply_filters('the_permalink', get_permalink());
echo json_encode($json);
echo ',';
endwhile;
echo ']';
endif;
?>
I know that echoing those elements is not the correct way to do it, and I'm doing something wrong on the encode, that's why it's pulling out without the right formatting.
I have been researching for days and I couldn't find a way to create a json_encode echoing and at the same time controlling the fields that it will show from a wordpress query.
I appreciate in advance any solution/lead to solve this.
You're adding it wrong in your loop. What you want to do is create an array, and present that array as json.
if($locations -> have_posts()):
$data = array();
while ($locations->have_posts()) : $locations->the_post();
// add the location stuff to the $data array
$data[] = array(
'id' => $pid,
'name' => get_the_title(),
// etc....
);
endwhile;
// present your json
echo json_encode($data);
endif;

Find Method Returning False

I am trying to execute a find in my script, but I believe my condition is returning false. I am trying to execute a find and pull all records that match the given value in my $data variable. I have tried to compare the BranchLicense.RegionCode to $data but no luck. I have also tried to compare it the _Session['Auth']['User']['region_code']. The $data variable is returning the correct value but the script does not return the proper records. What am I doing wrong here? Here is my code.
//echo '<pre>'; print_r($_SESSION); echo '</pre>';
//$this->loadModel('AuthAcl.Users');
$data = $_SESSION['Auth']['User']['region_code'];
//$data = $this->Users->find('all');
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' == $data)));
die(debug($new));
$this->layout = 'default';
//$this->set('branchLicenses', $this->BranchLicense->find('all', array(
//'conditions' => array('BranchLicense.RegionCode' === '$data'))));
Try as follows-
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' => $data)));
die(debug($new));

Categories