PHP - Pdo Output To Json
Hi there, Hoping some one can help. I am new to using PDO and i am trying to get data from my db to json I can get the data down to my $result so i know that part is working, my issue is with encoding it to json, if i pull a single record then it works if i pull all records then it doesn't, an i am not sure why $result = $page->read($_GET['pageid']); //check for data if ($result) { //page array $page_arr['pages'] = array(); while ($row =$result->fetch(PDO::FETCH_ASSOC)) { extract($row); $page_item = array( 'id'=> $id, 'title' => $title, 'pageid' => $pageid, 'pagecontent' =>html_entity_decode($pagecontent), 'mdkeywords' => $mdkeywords, 'description' =>$description, 'date_added' =>$date_added, 'hasAudio' => $hasAudio, 'excludeSearch' =>$excludeSearch ); //push to data array_push($page_arr['pages'], $page_item); } //print_r($page_arr['pages']); //If i enable this then i can see all the data //turn to json echo json_encode($page_arr['pages'], JSON_FORCE_OBJECT); //This is where my page is blank. } } else { echo json_encode(array('message'=>'nothing here!.')); }
Similar Tutorialshi, I was going through this tutorial: http://www.electrictoolbox.com/json-data-jquery-php-mysql/ here is my HTML Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script language="javascript" type="text/javascript"> function populateFruitVariety() { $.getJSON('search-by.php', {fruitName:$('#fruitName').val()}, function(data) { var select = $('#fruitVariety'); var options = select.attr('options'); $('option', select).remove(); $.each(data, function(index, array) { options[options.length] = new Option(array['variety']); }); }); } $(document).ready(function() { populateFruitVariety(); $('#fruitName').change(function() { populateFruitVariety(); }); }); </script> </head> <body> <form> Search by: <select name="name" id="fruitName"> <option>Please Select</option> <option id="Town" value="Town">Town</option> <option id="County" value="County">County</option> </select> Variety: <select name="variety" id="fruitVariety"> </select> </form> </body> </html> here is my PHP Code: [Select] $dbhost = "xxx"; $dbname = "xxx"; $dblogin = "xxx"; $dbpass = "xxx"; function dbConnect() { global $dbhost; global $dbname; global $dblogin; global $dbpass; $db = mysql_connect($dbhost, $dblogin, $dbpass) or die("could not connect to database: ".mysql_error()); mysql_select_db($dbname) or die("could not select database"); return $db; } function dbClose($db) { mysql_close($db); } // basis code ^^ $db = dbConnect(); $rows = array(); if(isset($_GET['Town'])) { $query = "SELECT DISTINCT rsCounties FROM pubs"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo json_encode($rows); } } if(isset($_GET['County'])) { $stmt = $pdo->prepare("SELECT rsCounty FROM pubs"); $stmt->execute(array($_GET['rsCounty'])); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } echo json_encode($rows); Can someone please help? I have the JQuery working but not the PHP?! here is a link to what I have at the moment: http://www.mypubspace.com/dashnew/index.html thanks I am returning the following through JSON: Code: [Select] $this->view->lead_query=$lead_query->fetchALL(); header('OK', true, 200); header('Content-type: application/json'); echo json_encode($this->view->lead_query); I am getting the results in this format: [{"client_name":"Steve Harris","state":"TX"}] Now if the above output was displayed without the square brackets [] I can populate the values in my form correctly. Is there a way i can return the output without the square brackets? I am using multiple levels of JSON data coming into php from a C# application, as in:
return new RootObject() { ID_Project = 4, Name_Project = "Test", Receiver_ID = 4, Receiver_Name = "ABCDE", UserID = 20, UserRole = new User_Role() { ID_User = 20, Role_User = "level 3", User_Role_Description = "U", UserGroup = new List<user_group>() { new User_Group() { ID_UserGroup = 30, Name_UserGroup = "usergroup8", UserID = 20 }, new User_Group() { ID_UserGroup = 31, Name_UserGroup = "usergroup9", UserID = 21 }, new User_Group() { ID_UserGroup = 32, Name_UserGroup = "usergroup10", UserID = 22 } } } }; i am having troubles accessing the second level: UserRole and 3rd level: User_Group in my php script. im currently trying like this: foreach ($phpArray as $key => $value) { echo "<h2>$key</h2>"; foreach ($value as $k => $v) { echo "$k | $v "; foreach ($v as $key1) { echo "$key1 "; } } } does anyone have an idea? Thanks, Revathy Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Well I have a script that executes a scan on a system set to run infinitely, and I need it to echo out a message each time it loops through, but I don't want it to echo out the message with the next loop message below it, and the next one below that etc... I've tried using the flush(); function and been messing around with that with no luck. For security reasons I don't want to release any of the processing code, but here is the basic construction of the script: <?PHP ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** $RepeatIt = -1; for($g=1; $g!=$RepeatIt+1; $g++) { ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** $ScanMessage = ":.:.: SCANNING THE HITLIST FOR MOBSTER: ".$MobName." (SCAN #$g) :.:.:"."<br/><br/>"; echo $ScanMessage; ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** } ?> At the moment it's returning: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #1) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #2) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #3) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #4) :.:.: So what I want it to do is just delete the scanning message and replace it with the next scan message so while running this script you would see just the number increment on the same line. Any suggestions? Thanks. im trying to access code in Code: [Select] array(1) { [0]=> object(stdClass)#4 (1) { ["error"]=> array(1) { [0]=> object(stdClass)#5 (2) { ["message"]=> string(33) "no results found (error code 458)" ["code"]=> string(3) "458" } } } } ive tryed echo $blog_posts[0]->error->code; but all i get is Notice: Trying to get property of non-object in /home/sites/inspiredanceacademy.com/public_html/sno-blog-test/lib/social_news_office.php on line 173 Hey guys I am Posting data over to a server file in Json and I need to know how I can add to the XML file. here is both codes.
function validate() { $xml = simplexml_load_file("stock.xml"); $sxe = new SimpleXMLElement($xml->asXML()); for($i = 1; $i < 801; $i++) { $newItem->addChild("name" , "null"); } $sxe->asXML("stock.xml"); echo $sxe->asXML(); $response = $_POST; $response["items"] = "Test output"; $response["description"] = "test 42 "; $response["json"] = json_encode($response); echo json_encode($response); }The red text is what I want this json script to do. Do I have to return back to my form to add to the XML file? Can json add to a xml file on its own? Thanks for your time! have a good day! Hi, I have two select boxes on my site like this: Language - Level and the user can keep adding more sets of select boxes. I need the data posted to be JSON encoded like this: {"LANG1":["German","Beginner"],"LANG2":["Polish","Advanced"]} etc How can i make this happen? I have some PHP which sends some user provided data to the client:
<?php header('Content-type: application/json'); $data=array( array('id'=>10,'firstname'=>'John','lastname'=>'Doe'), array('id'=>14,'firstname'=>'Jane','lastname'=>'Doe'), array('id'=>19,'firstname'=>'XSS!','lastname'=>'XSS!'), ); echo(json_encode($data)); ?>The client then displays the data: $.getJSON('getJSON.php', { something: 123 }, function(list) { var string = ''; for (var i in list) { string += '<li>< a href = "index.php?id=' + list[i]['id'] + '">' + list[i]['firstname'] + '</a></li>'; } $("#MyElem").html(string); });Does this represent any XSS risk? If so, how do I prevent it? My script is not acting like it should. I believe its because of the recent change in the api, (the new error array)? Before there was only one.... <?php $gamertag = 'l RaH l'; $url = "http://api.xboxleaders.com/user_api.php?gamertag=".str_replace(' ', '%20', $gamertag); $output = file_get_contents($url); // try to convert the response into a PHP object $obj = json_decode($output); if(!is_object($obj)) die("Error parsing JSON response\n"); //define variables $avatar = ($obj->user->avatar); $gold = ($obj->user->gold); print $avatar; print $gold; ?> if you print_r $object; it displays this {"error":{"code":200,"desc":"OK"}},{"user":{"gold":1,"gamertag":"l RaH l","avatar":"http:\/\/avatar.xboxlive.com\/avatar\/l%20RaH%20l\/avatarpic-l.png","gamerscore":12508,"reputation":20},"recent_games":[{"recent_game":{"title":"Halo: Reach","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1297287259&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/ih\/ew\/0Wdsb2JhbA9ECgR8GgMfVlohL2ljb24vMC84MDAwIAAAAAAAAP6fF5U=.jpg"}},{"recent_game":{"title":"Halo 3","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1297287142&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/Us\/3e\/1Wdsb2JhbA9ECgR8GgMfWSpVL2ljb24vMC84MDAwIAAAAAAAAPrxzU0=.jpg"}},{"recent_game":{"title":"AC Brotherhood","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504989&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/oK\/tp\/1Wdsb2JhbA9ECgUNGgMfVlonL2ljb24vMC84MDAwIAAAAAAAAPpGq78=.jpg"}},{"recent_game":{"title":"Fighters Uncaged","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504974&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/v+\/Au\/0Wdsb2JhbA9ECgUNGgMfVlsmL2ljb24vMC84MDAwIAAAAAAAAP4B4KA=.jpg"}},{"recent_game":{"title":"Assassin's Creed","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504852&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/L3\/mu\/0Wdsb2JhbA9ECgUNGgMfWStXL2ljb24vMC84MDAwIAAAAAAAAP6BeTA=.jpg"}}]} how can i also output $pages number into the json as well so i can use it for jquery Code: [Select] <?php // Start Buffer ob_start(); // Load Settings require '../../includes/config.inc.php'; // Require the database connection: require(MYSQL); // Number of records to show per page: $display = 6; // Determine how many pages there are... if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined. $pages = $_GET['p']; }else{ // Need to determine. // Default Query $count_q = "SELECT COUNT(id) FROM deals"; // Count the number of records: $r = @mysqli_query ($dbc, $count_q); $row = @mysqli_fetch_array ($r, MYSQLI_NUM); $records = $row[0]; // Calculate the number of pages... if ($records > $display) { // More than 1 page. $pages = ceil ($records/$display); } else { $pages = 1; } } // End of p IF. // Determine where in the database to start returning results... if (isset($_GET['s']) && is_numeric($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } // Make the query: $q = "SELECT id, url, views, deal_img, title, savings, DATE_FORMAT(expiry, '%a, %d %b %Y') AS expr FROM deals ORDER BY created_on DESC LIMIT $start, $display"; $r = @mysqli_query ($dbc, $q); // Run the query. if (mysqli_num_rows($r) > 0) { // Available. /* create one master array of the records */ $offers = array(); while ($offer = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $offers[] = array("id" => $offer["id"], "url" => BASE_APP_URL.'offer/'.$offer["url"].'/', "views" => $offer["views"], "image" => BASE_URL.'niftyuk-deal/'.$offer["deal_img"], "title" => $offer["title"], "savings" => $offer["savings"], "expr" => $offer["expr"]); } // End of WHILE loop. } /* output in necessary format */ header('Content-type: application/json'); echo json_encode($offers); ?> Hello, I can't get a json call to work in my php... Hope some one can see where I am going wrong and push me in the right direction. I have 3 values I am trying to send from the php file to the html. The output looks as if it should work, but is does not... So here is the php variable that does give me a result, but I have no idea why it does not show in the div. <?php $choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $dayPowerP = array( $row['choice']); ?> <?php $choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $monthPowerP = array($row['choice']); ?> <?php $choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $yearPowerP = array( $row['choice']); ?> <?php $outarr['dayPowerP'] = $dayPowerP; $outarr['monthPowerP'] = $monthPowerP; $outarr['yearPowerP'] = $yearPowerP; echo json_encode($outarr); ?> Now there are no errors, and this is what the output is so I would assume it should work as the right values are there and the right id..... Code: [Select] {"dayPowerP":["12.7240"],"monthPowerP":["145.0460"],"yearPowerP":["941.0370"]} I do not understand. Now the Jquery should be working as well... the ajax should be sending the post with json to carry the key data to make a clear result from the php and json should be doing it's job in the php file and the Jquery is do basic to have any issues, so that leaves my focus on the PHP at this time, but I do not see a proplem. Code: [Select] $(document).ready(function () { $('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) { var myDate = $(this).datepicker('getDate'); $('#apDiv1').html($.datepicker.formatDate('DD, d', myDate)); $('#apDiv5').html($.datepicker.formatDate('MM', myDate)); $('#apDiv7').html($.datepicker.formatDate('yy', myDate)); $.ajax({ type: "POST", url: "clickdates.php", data: {choice: dateText}, dataType: "json", success: function(json_data) { $('#apDiv2').html(json_data['dayPowerP']); $('#apDiv6').html(json_data['monthPowerP']); $('#apDiv8').html(json_data['yearPowerP']); } }) }}); }); The one thing that is odd. When I use 3 different php files, it works perfect, but that is not using json. Now that I am using json to return 1 call from the php, I am lost at this point, does anyone see what I can't... Thanks, Alan Please see http://www.socialnewsoffice.com/blog_posts?&display=2&api_key=b5cbd66dca99c49d1a6c3d which out puts a json response like this Code: [Select] [{ "blog_id":"3", "post_date":"Sat, 14 April 2012", "post_title":"Facebook's New Fan Page Learn How To Use Features", "article_img":"http:\/\/www.socialnewsoffice.com\/uploads\/17963.jpg", "post_content":"<p>This week saw the release of Facebook's latest functionality changes (Timeline for Businesses) that will shape the future of how businesses will market their campaigns, through the social media giant Facebook. A number of marketers are wondering how they will incorporate the new features in an attempt to progress and move forward with their online social media presence.<\/p>\r\n<p>Taking all the key changes in to consideration we have managed to create a guide on how to smoothly move with the times and embrace the new Facebook layout.<\/p>\r\n<p>Please read on below for helpful tips and tricks on how to excel with 'Timeline for Brands'<\/p>\r\n<h2>New Features Announced at the Facebook Marketing Conference:<\/h2>\r\n<p><strong>View and Apps:<\/strong> What was once known as Application pages has changed to 'Tabs'. These can now have customizable images linked with them and the order of them can be changed too. Below you can see from the screenshot what a customized Facebook Timeline looks like.<\/p>\r\n<p><strong>Pinning Content:<\/strong> With this new feature you can 'pin' a post to the very top of your Facebook Timeline. This is Very effective when working on a new campaign and is a great way to entice increased traffic to your tab or application page.<\/p>\r\n<p><strong>Featured 'Starred' Content:<\/strong> This feature allows you to select key content or imagery and extend it so it fits across your entire page. Therefore giving you featured content on your Facebook Timeline and making it more visible.<\/p>\r\n<p><strong>Cover Photos:<\/strong> Cover Photos are another great new feature that allow you to announce your latest campaign, welcome your following community or just simply show visitors to your timeline what you can do. There are some slight flaws with this feature though and will be addressed below.<\/p>\r\n<p><strong>Page Dimensions:<\/strong> Dimensions of application pages has now changed with the release of Facebook Timeline. If you happen to be an SML user then you have all the tools necessary to update your page on your own. If your using Involvers App Suite then those applications will be updated soon.<\/p>\r\n<p><strong>Removal of Default Landing Pages:<\/strong> The commonly used Facebook landing pages have been removed and replaced with various options to allow brands to drive content to application pages. These options allow you to use your cover photo and pinned content to attract users to your personal application pages. Despite the changes it is however still possible to link directly to application pages from ads, posts and outside of Facebook.<\/p>\r\n<h2>Getting Started with Timeline For Brand:<\/h2>\r\n<p>Firstly when accessing and logging in to your New Facebook Brand Page, you will see this admin message displayed below:<\/p>\r\n<p>When will my Page change to the latest design?<\/p>\r\n<p>To see a preview of what your new pages will look like, simply click on the green button at the top of your current pages. A second option is to wait until March 30th 2012 when all pages will be upgraded automatically.<\/p>\r\n<p>Where can I visit to learn more about how to use the new Pages?<\/p>\r\n<p><strong>There are a number of places you can visit to learn all you need to know about Pages:<\/strong><\/p>\r\n<ul>\r\n<li>To find out more about new features, download the Pages Overview guide by clicking here.<\/li>\r\n<li>If your wondering how to get started with Pages then download Facebook's full Pages Product Guide by clicking here.<\/li>\r\n<li>The Pages Learning video allows you to walk through the key features with Facebook's product experts.<\/li>\r\n<li>If you need answers to specific questions, visit Facebook's Help Centre.<\/li>\r\n<\/ul>\r\n<h2>How should I choose a cover photo for my Page?<\/h2>\r\n<p>Firstly select a unique image that represents your page. Facebook itself recommends using a photo of a popular menu item, album artwork or an image of your product being used by someone. You need to experiment with a number of different images that your audience responds positively to. Few key elements of Cover Images:<\/p>\r\n<p><strong>Each Cover image must be at least 399 pixels wide and must not contain the following:<\/strong><\/p>\r\n<ul>\r\n<li>Prices \/ Purchase information and displaying offers such as \"60% off this month\" are not permitted. Also 'Download this from our website' is not allowed.<\/li>\r\n<li>No email addresses, web addresses and any other contact information.<\/li>\r\n<li>References to clicking on or the use of Facebook interface elements such as Like or Share or any other Facebook Features.<\/li>\r\n<li>\"Tell your friends\" or \"Get it now\" or any other calls to action are not allowed in the latest version of Facebook Timeline.<\/li>\r\n<\/ul>\r\n<p>All Timeline cover imagery is public and therefore means anyone visiting your Page will be able to see exactly which image you have chosen. The photos you display must not be deceptive, false or misleading any way that infringes on third party intellectual property. You must also not encourage of incentivize other fellow users, friends or business associates to display the same cover image as yours on personal Timelines.<\/p>\r\n<p>To sum up we are extremely excited about the latest Facebook feature release this week. They constantly deliver new services that are amazing and incredibly innovative to the market place.<\/p>\r\n<p>Here at Northplanet we are commited to provide you with the latest information on the hottest online topics around, to keep you ahead in the game. We would love to hear some feedback from you on the brand new Facebook 'Timeline for Brands' release and invite you to visit our very own <a href=\"https:\/\/www.facebook.com\/northplanet\">Northplanet Facebook Timline page by clicking here.<\/a><\/p>", "tags":"facebook, new fan page", "views":"463", "categorie_id":"2", "post_url":"facebooks-new-fan-page-learn-how-to-use-features" },{ "blog_id":"2", "post_date":"Mon, 23 January 2012", "post_title":"Northplanet Engages New Talent!", "article_img":"http:\/\/www.socialnewsoffice.com\/uploads\/1263.jpg", "post_content":"<p>Big piece of news for the start of 2012 is…… I have landed a full time role in a leading Web Design and Development agency based in Greater Manchester. After a successful interview on New Years Eve, I had another reason to celebrate bringing in the New Year!!<\/p>\r\n<p>I was first attracted to Northplanet when I came across there website when searching for jobs online. I was impressed not only by the standard of web work but the direction the company where going in. Growing year by year and providing exceptional web solutions for a number of businesses spread across the UK.<\/p>\r\n<p>I contacted them instantly and have done some freelance work a few times in the last year for Directors Danny and Mike and was able to build up a strong working relationship that helped me land the interview at the end of the year.<\/p>\r\n<p>I begin my career at Northplanet next week and will post all offers\/promotions and deals on here in the nearfuture.<\/p>\r\n<p>Time to sign off and prepare for my new career!!<\/p>", "tags":"engages new talent, new staff, northplanet staff, christian thomas mizon", "views":"271", "categorie_id":"1", "post_url":"northplanet-engages-new-talent" }] here is my code that does this Code: [Select] if (mysqli_num_rows($r) > 0) { // Available. while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $results[] = array( 'blog_id' => ($row['ID']), 'post_date' => ($row['pd']), 'post_title' => (html_entity_decode($row['post_title'], ENT_QUOTES)), 'article_img' => ('http://www.socialnewsoffice.com/uploads/'.$row['article_img']), 'post_content' => ($row['post_content']), 'tags' => ($row['tags']), 'views' => ($row['views']), 'categorie_id' => ($row['categorie_id']), 'post_url' => ($row['post_url'])); } echo $json = Pretty_JSON(json_encode($results)); } i can access the json by using foreach($blog_posts as $post) { however what i need to do is add a value to the json like pages => 2 how could i do this? Okay so i know this is going to sound really stupid i just got out of school and now im in the real world here is the problem I dont know very much about how to work with JSON via PHP all i am trying to do is have the Script read data into an array from some text boxes then from the array into a JSON file the reading and the listing is all fine and dandy but only if i want the entire file how do i read data from a JSON file and only have it display data according to what i want so for example if i wanted to return data that matched an ID like you would do in MySQL like this ("SELECT * FROM catagories WHERE ID = '$id'") so how do i do that without a Database using a JSON File as a source for the data I'm trying to write a zend restful api and am return a json result. Everything works excepts when I am encoding a very large string such as a article with multiple paragraphs. The result is null in this case. Do I need to do something with the text before performing a json encode. Code: [Select] $this->getResponse() ->appendBody($this->_helper->json($article)); I have a json file returned by facebook e.g { "data": [ { "name": "Support! Muffin the fool (Oldham Chronicle FAKE)", "category": "Community", "id": "181377645219010", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|181377645219010|MvOBJKYtO7eT8JxMLtJ00HtGNxo" }, { "name": "Northplanet", "category": "Local business", "id": "132483460132622", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|132483460132622|AHXPNTZx7aihyQS_A9W6pR115U4" }, { "name": "Social Media Manger", "category": "Application", "id": "102650199811234", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|102650199811234|KeH0n1OKzZFtCkpa0lX1yJZ7NBE" }, { "name": "Top Ten Things To Remember Me By!", "category": "Application", "id": "375102030458", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|375102030458|H-mpQWrksu_2FzZ_eBNVzeD2Z1Y" } ] } $graph_url = "https://graph.facebook.com/$uid/comments=" . $access_token; $api = json_decode(file_get_contents($graph_url)); $name = $api->data->name; // this bit not storing the name not sure why Hi everyone. There are two nice script which are advanced for me to understand. There is a Knockout tournament scheduler class that makes image of the bracket. and there is a code that makes html of the bracket with jquery. I want to use the class with jquery. but I don't know how to do that and where to start. the class below needs to implement to this http://whileonefork.blogspot.com/2010/10/jquery-json-to-draw-elimination-single.html I attached the php script. please help me! Code: [Select] <?php class KnockoutGD extends Knockout { private $im = null; // GD-lib image resource. private $tc = 0; // Text color. public function getImage($tourName = '') { /* Returns a GD-lib image resource */ // Initial testing. if (empty($this->roundsInfo)) return null; // Dimensional parameters. $fh = imagefontheight(FONT); $fw = imagefontwidth(FONT); $lpad = 30; // Line (branch) padding before and after competitor names and after scores. $hpad = 20; // Outer horizontal image padding. $vpad = 60; // Outer vertical image padding. $lw = $this->getStrLen()*$fw + 3*$lpad; // Line (branch) width. Where getStrLen() gets the length of the longest string used in the image. // Initial calls. $dimensions = $this->getDimens($fh, $lw, $hpad, $vpad); $this->im = imagecreate($dimensions['x'], $dimensions['y']); $bg = imagecolorallocate($this->im, 255, 255, 255); // Set background color. $this->tc = imagecolorallocate($this->im, 0, 0, 0); // Text color. $this->mkStr($dimensions['x'] - $hpad - imagefontwidth(LFONT)*strlen($tourName), $dimensions['y'] - $vpad/2, $tourName, LFONT); // Print tournament name. // Initial positioning values from which drawing begins. $rx = $hpad; // Round X-position. $ry = $vpad; // Round Y-position. $depth = 1; // Branch depth. // Start drawing the tournament bracket/tree. foreach ($this->roundsInfo as $r => $info) { $n = $info[1]; // Number of expected players in round $r. // If a match is no yet created, then a placeholder is made so that the bracket structure is still printable. for ($m = 0; $m <= $n/2 - 1; $m++) { if (!$this->isMatchCreated($m, $r)) { $this->bracket[$r][$m]['c1'] = $this->bracket[$r][$m]['c2'] = null; $this->bracket[$r][$m]['s1'] = $this->bracket[$r][$m]['s2'] = -1; } } // Now we generate round branches. $x = $rx; $y = $ry; $bheight = pow(2, $depth) * $fh; // This is the height of a match-branch, which increases as the tree depth increases. ksort($this->bracket[$r]); foreach ($this->bracket[$r] as $m) { for ($i = 1; $i <= 2; $i++, $y += $bheight) { $this->mkStr($x+$lpad, $y, $m['s'.$i] == -1 ? 'Undecided' : $m['c'.$i]); $this->mkStr($x+$lw-$lpad, $y, $m['s'.$i] == -1 ? '?' : $m['s'.$i]); $this->mkLine($x, $y+$fh, $x+$lw, $y+$fh); } $this->mkLine($x+$lw, ($y+$fh)-$bheight, $x+$lw, ($y+$fh)-2*$bheight); } // Get ready for next loop. $rx += $lw; $ry += $bheight/2; $depth++; } // Add final branch/line for the tournament winner $fr = end(array_keys($this->roundsInfo)); // Final round. $s1 = $this->bracket[$fr][0]['s1']; $s2 = $this->bracket[$fr][0]['s2']; $winner = (!array_key_exists(0, $this->bracket[$fr]) || $s1 == -1 || $s2 == -1 || $s1 === $s2) ? '?' : (($s1 > $s2) ? $this->bracket[$fr][0]['c1'] : $this->bracket[$fr][0]['c2']); $this->mkStr($rx+$lpad, $ry, 'Winner: ' . $winner); $this->mkLine($rx, $ry+$fh, $rx+$lw, $ry+$fh); // Now, we print the round titles. array_push($this->roundsInfo, array('Champion', 1)); // Add fictitious round for printing purposes only. foreach (array_reverse($this->roundsInfo) as $r) { $this->mkStr($rx+$lpad, $vpad/3, $r[0], LFONT); $rx -= $lw; // Move back one round/column. } array_pop($this->roundsInfo); // Remove fictitious round entry again. return $this->im; } private function mkLine($x0, $y0, $x, $y) { /* Wrapper for function that creates a line. */ imageline($this->im, $x0, $y0, $x, $y, $this->tc); } private function mkStr($x, $y, $str, $font = false) { /* Wrapper for function that writes a string. */ imagestring($this->im, $font ? $font : FONT, $x, $y, $str, $this->tc); } private function getDimens($fontHeight, $lineWidth, $horizPad, $vertPad) { /* Returns image dimensions based on the tournament bracket. */ /* Vertically: Each match-branch is outputted like this: Team A ----------- Padding Team B ----------- Padding ... where "Padding" and "Team X" are of height $fontHeight, and "------" are branch lines with approximately no height. Horizontally: Each branch is outputted like this: ----- Team A ------ | ----- Team C ------ | ----- Team B ------ ... where "Team X" branch has an absolute length of $lineWidth. The above therefore illustrates a length of 2*$lineWidth. The image length, $x, must be: $horizPad + number_of_rounds * $lineWidth + $horizPad And the image height, $y, must be: $vertPad + number_of_matches_in_first_round * 4*$fontHeight + $vertPad ... since the first round contains the most matches. */ $frGames = count($this->bracket[1]); // Number of games in the first round. $playInExists = !empty($this->bracket[0]) ? true : false; /* The y-size of the image must be calculated accordingly to the above description. Though, if a play-in round exists, then the play-in round is potentially the round which requires the most vertical space to draw. In this case we scale the image as if the play-in round was the first round. Due to the nature of the tournament bracket, this means that there are twice as many games in that round. */ $y = 2*$vertPad + ($playInExists ? $frGames*2 : $frGames) * 4*$fontHeight; /* The x-size of the image is proportional to the number of rounds in the tournament, where the proportionality constant is the length of a branch, $lineWidth, ie. the width of a round. Since the number of players in the first round is equal to 2^R, where R is a whole number, and denotes the number of rounds required in the tournament, then R = log(players, 2), where "players" also can be found by 2 * matches_in_first_round (2 players pr. match). Like above, if a play-in round exists the x-size of the image must be changed. In this case, we merely add the length of a branch to the total x-size, since all branches are equal in length. Besides that, we add another whole branch length for the Winner/Champion branch, which technically is not a part of the tournament bracket, but is shown anyway. */ $x = 2*$horizPad + (log($frGames*2, 2) + ($playInExists ? 1 : 0) + 1) * $lineWidth; return array('x' => $x, 'y' => $y); } private function getStrLen() { /* Returns the length of longest string used in either rounds. This is done by looking in both play-in round and first round, since all competitors are to be found there. */ $len = 0; foreach (array_merge(array_key_exists(0, $this->bracket) ? $this->bracket[0] : array(), $this->bracket[1]) as $m) { if (($newlen = strlen($m['c1'])) > $len) $len = $newlen; if (($newlen = strlen($m['c2'])) > $len) $len = $newlen; } foreach ($this->roundsInfo as $arr) { if (($newlen = strlen($arr[0])) > $len) $len = $newlen; } return $len; } } ?> I am writing a simple connector for an android application and my json_encode is outputting enclosing the array with []. This is throwing an error during the decode process because the array needs to start with a {. I know this has to do with the $output[] in the loop, but I dont know how to pass the values into the array any other way. I even tried to trim after doing the encode. Here is my code: Code: [Select] <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $agency= mysql_query("SELECT agencyname FROM agency WHERE status ='Prospect' ORDER BY agencyname DESC")or die(mysql_error()); while($ageinfo = mysql_fetch_assoc($agency)) { $output[] = $ageinfo; } print(json_encode($output)); ?> Hi all, I am sure this is simple, but I just can't wrap my head around a suitable way of doing this! Basically I have my JSON result as something like : Code: [Select] Array ( [result] => success [source] => gotBits [success] => 64 ) What I simply want to do is get the [success] output and store it as a variable. I have been looking at json_decode, but I cant find any examples for arrays, just strings? Can you push me in the right direction? Hello, I am trying to understand how to post several actions and return 1 call. I am new to this so I thank you for your understanding. Here is the full story, I have the Jquery working now that 1 "onSelect" will post to 6 php files, but it takes forever for all the calls to return to the div. From my reading, I need to put the 6 php files into one php file, and then return this with JSON... here is where my trouble begins. Now here is the current php file that I have put into 1 php file (placed as they were working when in 6 files to the Jquery below) <?php $choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d"); $con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$dayPower."' group by date";$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $d = array(); while($row = mysql_fetch_assoc($res)) {; echo json_encode($d); } ?> <?php $choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d"); $con =$con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); mysql_connect("localhost","root","mackie1604"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = " SELECT HOUR(time) as h, power FROM feed WHERE date = '".$choice."' ORDER BY HOUR(time)"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $daypower = array(); while($row = mysql_fetch_assoc($res)) { $daypower[] = $row['power']; } ?> <script type="text/javascript"> $(document).ready(function() { var chart = new Highcharts.Chart({ chart: { renderTo: 'apDiv4', defaultSeriesType: "column", }, events: { marginTop: 1, marginRight: 1, marginBottom: 1, marginLeft: 4 }, credits: { enabled: false, }, title: { text: null, }, subtitle: { text: null, }, xAxis: { labels: { y: 15 }, categories: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'] }, yAxis: { min: 0, max: 2000, title: { text: null }, labels: { align: 'left' } }, legend: { enabled: false }, tooltip: { formatter: function() { return ''+ this.x +': '+ this.y +' Watt hr'; } }, plotOptions: { column: { pointPadding: 0.02, borderWidth: 0 } }, series: [{ name: '', color: '#50B432', data: [<?php echo join($daypower, ', '); ?>] }] }); }); </script> <?php $choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); echo $row['choice'].'<br />'; ?> <?php $choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = " SELECT MONTH(date) AS m, SUM(power/1000) AS monthpower FROM feed WHERE MONTH(date) = '".$choice."' GROUP BY DAY(date) ORDER BY DAY(date)"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $monthpower = array(); while($row = mysql_fetch_assoc($res)) { $monthpower[] = $row['monthpower']; } ?> <script type="text/javascript"> $(document).ready(function() { var chart = new Highcharts.Chart({ chart: { renderTo: 'apDiv9', defaultSeriesType: "column" }, events: { marginTop: 1, marginRight: 0, marginBottom: 0, marginLeft: 1 }, title: { text: null, }, subtitle: { text: null, }, xAxis: { labels: { y: 15 }, categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'] }, yAxis: { min: 0, max: 20, title: { text: null }, labels: { align: 'left' } }, legend: { enabled:false }, tooltip: { formatter: function() { return ''+ this.x +': '+ this.y +' kWh'; fontWeight: 'normal' fontSize: '1px' } }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: '', color: '#50B432', data: [<?php echo join($monthpower, ', '); ?>] }], credits: { enabled:false, }, }); }); </script> <?php $choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); echo $row['choice3'].'<br />'; ?> <?php $choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("xxxxxx","xxxxxx","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = " SELECT MONTH(date) AS y, SUM(power/1000) AS yearpower FROM feed WHERE YEAR(date) = '".$choice."' GROUP BY MONTH(date) ORDER BY MONTH(date)"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $yearpower = array(); while($row = mysql_fetch_assoc($res)) { $yearpower[] = $row['yearpower']; } ?> <script type="text/javascript"> $(document).ready(function() { var chart = new Highcharts.Chart({ chart: { renderTo: 'apDiv10', defaultSeriesType: "column" }, events: { marginTop: 1, marginRight: 1, marginBottom: 1, marginLeft: 1 }, credits: { enabled: false, }, title: { text: null, }, subtitle: { text: null, }, xAxis: { labels: { y: 15 }, categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] }, yAxis: { min: 0, max: 500, title: { text: null }, labels: { align: 'left' } }, legend: { enabled: false }, tooltip: { formatter: function() { return ''+ this.x +': '+ this.y +' kWh'; } }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: '', color: '#50B432', data: [<?php echo join($yearpower, ', '); ?>] }] }); }); </script> Here is the Jquery that was working to send to the 6 different php files (to help you understand what my goal is... Code: [Select] $('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) { var myDate = $(this).datepicker('getDate'); $('#apDiv1').html($.datepicker.formatDate('DD, d', myDate)); $('#apDiv5').html($.datepicker.formatDate('MM', myDate)); $('#apDiv7').html($.datepicker.formatDate('yy', myDate)); $('#apDiv2').load('dayPower.php', {choice: dateText}, function() { $(this).show(); }); $('#apDiv4').load('dayGraph.php', {choice: dateText}, function() { $(this).show(); }); $('#apDiv6').load('monthPower.php', {choice: dateText}, function() { $(this).show(); }); $('#apDiv9').load('monthGraph.php', {choice: dateText}, function() { $(this).show(); }); $('#apDiv8').load('yearPower.php', {choice: dateText}, function() { $(this).show(); }); $('#apDiv10').load('yearGraph.php', {choice: dateText}, function() { $(this).show(); }); }}); }); I am back to this as what I was changing became a mess, and I am starting from what was working.... How do I get JSON to send and return from the one PHP file. Thank You, Alan |