Jump to content

Search the Community

Showing results for tags 'json'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

  1. hello, i am new in php and i would like to develop a login screen in android. my server side is developed in php and for some reason i get every request the follwoing error: "no such file or directory". i have 1 index file and 3 files insdie the "include" directory. this is my files code: index.php <?php /** * Created by PhpStorm. * User: matant * Date: 4/29/2015 * Time: 4:57 PM */ $data = $_SERVER['HTTP_JSON']; $data = json_decode($data); $temp = $data->tag; if($temp == 'login') { $tag = $data->tag; $temp = 'insdieif'; require_once 'include/DB_Functions.php'; $db = new DB_Functions(); $response = array("tag" => $tag, "error"=>FALSE); //login if($tag == 'login') { $email = $data->email; $password = $data->password; $user = $db->getUserDet($email,$password); if($user != false){ $response["error"] = FALSE; $response["user"]["username"] = $user["usern"]; $response["user"]["email"] = $user["email"]; echo json_encode($response); }else { $response["error"] = true; $response["error_msg"] = "Incorrect Email or Password!"; echo json_encode($response); } }else { $response["error"] = true; $response["error_msg"] = "This is not Login request!"; echo json_encode($response); } } else { $response["tag"] = $temp; $response["error"] = true; $response["error_msg"] = "tag parameter is missing"; echo json_encode($response); } DB_Functions.php <?php /** * Created by PhpStorm. * User: matant * Date: 4/29/2015 * Time: 3:57 PM */ class DB_Functions { private $db; function _contrust() { require_once 'DB_Connect.php'; $this->db = DB_Connect(); $this->db->connect(); echo $this->db; } function _destruct() { // $this->close(); } public function getUserDet($email, $pass) { $res = mysql_query("SELECT * FROM users WHERE email = '$email'") or die (mysql_error()); $num_of_rows = mysql_num_rows($res); if ($num_of_rows > 0) { $res = mysql_fetch_array($res); $restemp = $res['password']; if ($pass == $restemp) return $res; else return false; } } } ?> DB_Connect.php: <?php /** * Created by PhpStorm. * User: matant * Date: 4/29/2015 * Time: 3:47 PM */ class DB_Connect{ function _construct(){ } function _destruct(){ } public function connect(){ require_once 'Config.php'; $con = mysql_connect("DB_Host","DB_User","DB_password"); if(!$con) { die('could not connect:'.mysql_error()); } else { mysql_select_db(DB_database, $con); } return $con; } public function close() { mysql_close(); } } ?> Config.php: <?php /** * Created by PhpStorm. * User: matant * Date: 4/29/2015 * Time: 3:35 PM */ define("DB_Host","sqlserver"); define("DB_User","user"); define("DB_password","pass"); define("DB_database","b12_16183751_gpsport"); ?>
  2. Hi, I've got this JSON output: {"result":"success","clientid":null,"serviceid":null,"pid":null,"domain":"testdomain.com","totalresults":"1","startnumber":0,"numreturned":1,"products":{"product":[{"id":"3804","clientid":"1401","orderid":"3276","pid":"53","regdate":"2010-02-14","name":"Basic","groupname":"Plans","domain":"testdomain.com","dedicatedip":"","serverid":"4","servername":"serverx.com","serverip":"","serverhostname":"","firstpaymentamount":"7.99","recurringamount":"7.99","paymentmethod":"wibble","paymentmethodname":"Credit\/Debit Card","billingcycle":"Monthly","nextduedate":"2010-02-14","status":"Terminated","username":"dcdqw","password":"z1nmY1p4Y9","subscriptionid":"","promoid":"0","overideautosuspend":"","overidesuspenduntil":"0000-00-00","ns1":"","ns2":"","assignedips":"","notes":"","diskusage":"0","disklimit":"1000","bwusage":"0","bwlimit":"50000","lastupdate":"2015-05-01 06:01:17","customfields":{"customfield":[{"id":"36","name":"ThisUserID","value":"1243214"}]},"configoptions":{"configoption":[]}}]}} ... and I'm trying to get the value for ThisUserID but I'm struggling so much with the arrays! I've copied it into http://jsonviewer.stack.hu so I can understand it more but just can't get that value. I understand: $clientid = $arr->clientid; ... but can't work out how to drill deeper. Any help appreciated
  3. Hi I have a json data : { "email": "john@john.fr", "line_items": [ { "sku": "123456789", "price": "0.67", "price_with_tax": "4.00", "tax_lines": [ { "title": "tax010", "rate": 0.01, "price": "1.11" }, { "title": "tax00200", "rate": 0.02, "price": "2.22" } ] }, { "sku": "012345666", "price": "1.67", "price_with_tax": "5.00", "tax_lines": [ { "title": "tax0003000", "rate": 0.03, "price": "3.33" } ] } ] } and I try put this data in mySql. First data have a good value but second have a wrong data on 'price_tax1' and 'price_tax2' in mySql : Here is my MySql 1st item :::: good value email:john@john.fr sku:123456789 price:0.67 price_with_tax:4.00 price_tax1:1.11 price_tax2:2.22 2nd item :::: email:john@john.fr sku:012345666 price:1.67 price_with_tax:5.00 wrong value :::: price_tax1:1.11 price_tax2:2.22 here is my code : $jsondata = file_get_contents($jsondata); $dataDecode = json_decode($jsondata); $email = $dataDecode->email; try { $dtbs = new PDO($dsn_dev, $pdo_user, $pdo_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch (Exception $e) { die('Error : ' . $e->getMessage()); } try { foreach ($dataDecode->line_items as $obj) { $var_sku = $obj->sku; $var_price = $obj->price; $var_price_with_tax = $obj->price_with_tax; $taxNewArray = array(); foreach ($dataDecode->line_items[0]->tax_lines as $obj2) { array_push($taxNewArray , $obj2); } $val1st = array_shift($taxNewArray); $val2nd = array_pop ($taxNewArray); $var_tax1 = $val1st->price; $var_tax2 = $val2nd->price; $stmt = $dtbs->prepare("INSERT INTO $tabledata ($mysql_email, $mysql_sku, $mysq_price, $mysql_price_with_tax, $mysql_price__tax1___line_items, $mysql_price__tax2___line_items ) VALUES (:email, :sku, :price, :price_with_tax, :price_tax1, :price_tax2)"); $stmt->execute(array(':email'=>$email, ':sku'=>$var_sku, ':price'=>$var_price, ':price_with_tax'=>$var_price_with_tax, ':price_tax1'=>$var_tax1, ':price_tax2'=>$var_tax2 )); } } catch(Exception $e) { throw $e; } How can I put goog value of 2nd data in mySql ? thanks
  4. I am trying to display Json data using PHP but I have ran into a problem. This is the json: }, { "node_title": "Room", "Room description": "This is Room 1", "Room name": "Room 1", "Room Type": "Bedroom", "Room attributes": [ ] }, { "node_title": "Room", "Room description": "This is Room 2", "Room name": "Room 2", "Room Type": "Bedroom", "Room attributes": [ This is my PHP: <?php $code = isset($_POST['search']) ? $_POST['search'] : '123nocode123456'; $roomjson = file_get_contents("http://my.json.com/". $code); $roomobj = json_decode($roomjson); ?> <?php echo '<div role="tabpanel"> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>'; if (empty($roomobj)) { echo '</div>'; }else{ if ($roomobj{0}->{'Room Type'} == 'Bedroom') { echo '<li role="presentation"><a href="#bedroom1" aria-controls="bedroom1" role="tab" data-toggle="tab">'; echo ($roomobj{0}->{'Room name'}); echo '</a></li></div>'; ?> The problem is, I have two json 'nodes' that have the same 'Room Type' value, so how can I differentiate between the two? But I need to display both of them. I think I can use foreach but I need the values 'Room Name' to be in separate <li>.
  5. Hi, My codes does not show any Latitude or Longitude but it did last night when I started writing this code?! $postcode = 'BN113ED'; $response = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($postcode) . '&sensor=true'); $response = json_decode($response); $lat = $response->results[0]->geometry->location->lat; $long = $response->results[0]->geometry->location->lng; here is the URL that shows the JSON http://maps.googleapis.com/maps/api/geocode/json?address=bn113ed&sensor=true
  6. Evening everyone and Merry X-Mas (Happy Holidays) or whatever fits you best.... I have been trying over and over for about 12 hours to figure out how to get data from a specific JSON response and assign the specific values to a new array key/value pair. The various ways I have tried to figure this out are numerous so i'm going to avoid the runnig list of "I trieid this...and this...and this... etc etc." just understand I have reached a dead end point where I need help badly. Here is what our end goal is: "The company" is a "service industry" provider (plumbing, electrical etc. etc.) who wants to dispatch its technicians to new jobs based on which technician has the shortest travel time from any existing address where they already have a scheduled appointment that day and has available time in there schedule. Thus the dispatching system when a new service call is entered is going to give "recommended" technicians (up to 4) to be assigned the new service call based on the above mentioned criteria. (Efficient routing to save company gas cost) 1.) We have a "New service" street address assigned to the $to variable: $to = "4813 River Basin Dr S, Jacksonville FL 32207"; 2.) We will have "records" array which containes a series of records, each record consists of a ticket# a technician id# and a street address: $records = array( array("DV1012","30453423","9890 Hutchinson Park Dr Jacksonville, FL 32225"), array("DB3434","30404041","821 Orange Ave Crescent City, FL 32112"), array("DB3434","30605060","1972 Wells Road, Orange Park FL 32073"), array("DB4578","30605060","2 Independent Drive, Jacksonville FL 32202"), array("DB7841","30605060","5000 Norwood Avenue, Jacksonville FL 32208"), array("DB3235","30605060","9501 Arlington Expressway, Jacksonville FL 32225"), array("DB7894","30605060","Massey Avenue, Jacksonville, FL 32227"), array("DB2020","30121212","11200 Central Pkwy Jacksonville, FL 32224") ); 3.) We are going to prepare the records array for submission to Google's Distance Matrix API by URL encoding each array value into a single variable and then submit it: foreach ($records as $key => $value) {$from = $from.urlencode($value[2])."|";} $to = urlencode($to); $data = file_get_contents("//maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&units=imperial&mode=driving&sensor=false"); $res=json_decode($data) or die("Error: Cannot read object"); You may look at the ACTUAL live Google response from this here: http://tiny.cc/i6eerx (We have applied <pre> and var_dump($res) to the output) We are looking to get the following information back: The distance and travel time between the "New Service" address ($to) and each of the address' in the $records array ($from), now once that information is returned from Google (JSON response) we need to parse the response and narrow it down to 4 or less (Based on the 4 lowest drive times) to form a new array which ends like this: $results = array( array("DV1012","30453423","2.3 Miles","8 mins"), array("DB3434","30404041","2.8 Miles","9 mins"), array("DB3434","30605060","4.6 Miles","13.8 mins"), array("DB4578","30605060","5.7 Miles","15.2 min") ); OUR PROBLEM: Everything up until the the Google API response is fine, but iterating over the multidimensional arrays within multidimensional arrays of the JSON response is just not coming together in my head (or 2 dozen code attempts). I am able to ECHO an individual value like ( echo $res->rows[0]->elements[0]->distance->text; ) but this has no value for the end result i need to get to. My last thoughts and efforts was that that I was going to have to embed foreach statements within foreach statements to drill down through the various arrays but that hasn't worked very well and it seems like it shouldn't be how it has to be done. I would appreciate any help in showing me how the iteration code should be written and any explanation about the code so i can wrap my head around it.
  7. Hello I am having an issue with encoding an array to JSON, my array seems to be formed correctly but when I try and echo the json_encode version I get "null". I echo the JSON error code and it is "0" indicating no issue.. I have read that non UTF-8 characters can be an issue, but this is simple data, no strange characters... but I added the utf8_encode anyway.... Here is my code: $dataArray = array( 'title' => 'Test Item', 'icon_url' => 'http://url/api/testimage.jpg', 'item_id' => '12345', 'expiration' => 600 ); utf8_encode($dataArray); $responsArray = array( 'success' => '1', 'data' => $dataArray ); utf8_encode($responsArray); header('Content-type: application/json'); echo print_r($responsArray); echo json_encode ($responseArray); echo json_last_error(); Any thoughts would be appreciated
  8. Can anyone help by shedding some light with a little problem I encounter using JSON endpoint requests. I'm not very good with PHP. When the endpoint is called and finds no data, I want to replace it with a local image source. In this case, I am calling brewery->logo_url. Most entries have endpoints, but some don't. When an image link is found at the endpoint, it throws off my layout. You can see the ones that look off. They align to the left. I want to replace with a logo default image each time this happens, with hopes to set the layout adjust back to normal. Here's my working document http://graintoglass.com/fb/tap-menu-test.php and here's the JSON. http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short Code Effort <?php $url = 'http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short&servingtype=bottlecan'; $curl_session = curl_init($url); curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($curl_session, CURLOPT_TIMEOUT, 10); $data = curl_exec($curl_session); curl_close($curl_session); $beer_list = json_decode($data); echo '<p class="last-updated">Last Updated: ' . date("m/d/Y") . '</p>'; echo '<h1 class="page-title">Bottle List</h1>'; echo '<p class="page-intro">Not only do we serve a hefty list of brews on tap, we also offer an exclusive list of beers in bottle. Our bottle list is constantly changing so the occasional return visits to browse this list is the best way to stay up to date. Take a look!</p>'; foreach ($beer_list as $beer) { echo '<article class="beer-entry"> <div class="beer-image"><img src="'.$beer->brewery->logo_url.'" /></div> <div class="beer-info"> <p class="brewery-name">'.$beer->brewery->name.' — '.$beer->brewery->origin.'</p> <h2 class="beer-name">'.$beer->beer->name.'</h2> <p class="beer-style">Beer Style: '.$beer->beer->style.'</p> <p class="beer-description">'.$beer->descriptions->short_description.'</p> <p class="beer-abv">ABV: '.$beer->beer->abv.' / IBU: '.$beer->beer->ibu.'</p> <p class="beer-ibu"></p> </div> <div class="clearfix"></div> </article> '; } echo '<p class="page-bottom">If you would like to see more of our food and beer options, <a href="https://www.graintoglass.com" target="_blank">visit our website</a>.</p>'; ?>
  9. I was pointed in this direction by a friend so firstly, hello I'm having some teething problems (basically can't get my head around it) and wondered if anyone would be able to have a look at a script for me (beer money may be provided) I'm currently using a php script which grabs information from a API with curl (JSON format). I'm limited to a number of requests an hour so my plan was to read the file, insert the data into a mysql table so that I could re-read over and over again with no limitations. Then use a script to run every few hours to grab the data. The script I created works however it's a bit buggy with regards to what it does if information is already in the table. If there isn't a previous entry then it inserts everything fine. The JSON data is a multi depth array, and deals with images as well as data so for me, it's rather complex. What I want the script to do is this. Each item is a property (letting agent website) Check to see if the property exists in the database and the JSON. If there is no record in the database, then insert in. If there is a record in the database, update that record. If there is a property in the database which isn't in the JSON file, then delete it from the database. This is basically the same plan for each sub array (pictures, floorplans, etc) however the images are copied from the url given (hosted on amazon) to my own host in order to speed up loading times, etc. i've added a copy of the code but obviously its going to be stupidly hard to understand. Is there any way this could be split into different functions to try and sort it out? haha <?php $ch = curl_init(); /* Section 1 */ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, 'URL'); //prepare the field values being posted to the service $data = array("appkey" => "KEY","account" => "ACCOUNT" ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //make the request $result = curl_exec($ch); $properties = json_decode($result, true); $properties = $properties['properties']; //pr($parsed_json); foreach($properties as $key => $value) { /* Set the vars */ $microTime = microtime(); $time = time(); $cat_id = $value['category_id']; $price = $value['price']; if ($value['category_id'] == "1") { $price_after = $value['qualifier_name']; } else { $price_after = $value['freq_name']; } $full_address = $value['full_address']; $address_1 = $value['address_1']; $address_2 = $value['address_2']; $address_3 = $value['address_3']; $address_4 = $value['address_4']; $address_5 = $value['address_5']; $bedrooms = $value['bedrooms']; $bathrooms = $value['bathrooms']; $summary = $value['summary']; $description = $value['description']; $type_name = $value['type_name']; $status = $value['status']; $feature_1 = $value['feature_1']; $feature_2 = $value['feature_2']; $feature_3 = $value['feature_3']; $feature_4 = $value['feature_4']; $lat = $value['lat']; $long = $value['lng']; /* Delete the properties from the database which can't be found in the file */ $searchProp = "SELECT property_id FROM props WHERE property_address_full = '$full_address' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $searchProp)) { if (!$whereStatement) { $whereStatement = "WHERE property_id != $row[property_id]"; } else { $whereStatement .= " OR property_id != $row[property_id]"; } // Set the whereStatement for deleting properties with no ID $deleteProp = "DELETE FROM props $whereStatement"; if ($result = mysqli_query ($linkq, $deleteProp)) { $totalPropsDeleted++; echo "Properties deleted $deleteProp"; $deleteimg = "DELETE FROM props_images $whereStatement"; if ($result = mysqli_query ($linkq, $deleteimg)) { echo ("Images Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deleteepc = "DELETE FROM props_epcs $whereStatement"; if ($result = mysqli_query ($linkq, $deleteepc)) { echo ("EPCs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletepdf = "DELETE FROM props_pdf $whereStatement"; if ($result = mysqli_query ($linkq, $deletepdf)) { echo ("PDFs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletefloorplan = "DELETE FROM props_floorplans $whereStatement"; if ($result = mysqli_query ($linkq, $deletefloorplan)) { echo ("Floorplans Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } } else { echo "Nothing to delete"; } } echo "<br />"; /* Check to see if the property exists currently */ $existCheck = "SELECT * FROM props WHERE property_address_full LIKE '%$full_address%' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $existCheck)) { $row_cnt = mysqli_num_rows($result); if ($row_cnt) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { echo "Property Exists - $full_address"; if (($row[property_price] != $price) || ($row[property_summary] != $summary) || ($row[property_description] != $description)) { $dateUpdated = "property_updated = $microTime,"; } else { $dateUpdated = "property_updated = property_updated,"; } /* Property exists so update the property info */ $updateProp = "UPDATE props SET property_advertised = property_advertised, $dateUpdated property_catid = '$cat_id', property_price = '$price', property_price_after = '$price_after', property_address_full = '$full_address', property_address_1 = '$address_1', property_address_2 = '$address_2', property_address_3 = '$address_3', property_address_4 = '$address_4', property_address_5 = '$address_5', property_bedrooms = '$bedrooms', property_bathrooms = '$bathrooms', property_summary = '$summary', property_description = '$description', property_type = '$type_name', property_status = '$status', property_feature_1 = '$feature_1', property_feature_2 = '$feature_2', property_feature_3 = '$feature_3', property_feature_4 = '$feature_4', property_lat = '$lat', property_long = '$long' WHERE property_id = '$row[property_id]'"; if (mysqli_query ($linkq, $updateProp)) { $totalPropsUpdated++; echo (" & Updated"); } else { echo (" & Error Updating"); } echo ("<br />\n"); /* Delete all the photos for this property as it doesn't matter if they are added again */ $deletePhotos = mysqli_query ($linkq, "DELETE FROM props_images WHERE property_id = $row[property_id] OR property_id = ''"); printf("Images Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current images and add back to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$row[property_id]', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted ($row[property_id]) ($imagename) ($image_main)\n"); if (!file_exists('images/props/'. $imagename .'.jpg')) { /* Try and copy the image from the url */ $file = 'https://utili-media.s3-external-3.amazonaws.com/stevemorris/images/' . $imagename . '_1024x1024.jpg'; $newfile = 'images/props/' . $imagename . '.jpg'; if (!copy($file, $newfile)) { echo "- Failed to Copy\n"; } else { echo "- Image Copied"; /* Resize the image and create a thumb nail */ $image = new SimpleImage(); $image->load('images/props/' . $imagename . '.jpg'); $image->resizeToWidth(240); $image->save('images/props/thumb/' . $imagename . '.jpg'); } } else { echo ("- Nothing to upload, image exists"); } echo "<br />\n"; } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the image loop */ /* Delete all the epcs for this property as it doesn't matter if they are added again */ $deleteEpcs = mysqli_query ($linkq, "DELETE FROM props_epcs WHERE property_id = $row[property_id]"); printf("EPCs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current EPCs and insert into the database */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epc loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deletePdfs = mysqli_query ($linkq, "DELETE FROM props_pdf WHERE property_id = $row[property_id]"); printf("PDFs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current PDFs and insert into the database */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the PDF loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deleteFloorplan = mysqli_query ($linkq, "DELETE FROM props_floorplans WHERE property_id = $row[property_id]"); printf("Floorplans Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current Floorplans and insert into the database */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the Floorplan loop */ } /* close the property while loop */ } else { /* close the if row exists loop */ /* Insert the property as it doesn't exist in the database */ $insert = "INSERT INTO props VALUES ('', '$time', '', '$cat_id', '$price', '$price_after', '$full_address', '$address_1', '$address_2', '$address_3', '$address_4', '$address_5', '$bedrooms', '$bathrooms', '$summary', '$description', '$type_name', '$status', '$feature_1', '$feature_2', '$feature_3', '$feature_4', '$lat', '$long', '', '')"; if (mysqli_query ($linkq, $insert)) { $totalPropsAdded++; echo ("Property Inserted - $value[full_address]<br />"); /* get the property ID from the newly added property */ $getPropID = mysqli_query ($linkq, "SELECT property_id FROM props ORDER BY property_id DESC LIMIT 1"); while ($rowNew = $getPropID->fetch_array(MYSQLI_ASSOC)) { $new_property_id = $rowNew[property_id]; } /* Loop the current images and add to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$new_property_id', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted Image ($new_property_id) ($imagename) ($image_main)<br />\n"); } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the images loop */ /* Loop the current epcsand add to the database and asign the property id */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epcs loop */ /* Loop the current pdfs and add to the database and asign the property id */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the pdfs loop */ /* Loop the current floorplans and add to the database and asign the property id */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the floorplans loop */ } else { echo ("Insert Error"); } /* close the insert property */ } /* close the row count loop */ } /* close the property exists loop */ } /* close everything */ curl_close($ch); mysqli_close ($linkq); ?>
  10. Good afternoon, I am working on a project that gives the user a data table and a google chart (using the api) based on what the user selects for a <select> <option>. Index.PHP code: <form> <select name="users" onchange="showUser(this.value);drawChart();"> <option value=""> Select a Metal: </option> <?php //connection details $query = "SELECT TOP(31) tblMetalPrice.MetalSourceID, tblMetalSource.MetalSourceName from tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID=tblMetalSource.MetalSourceID ORDER BY tblMetalPrice.DateCreated DESC "; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_object ($result)) { echo "<option value='".$row->MetalSourceID ."'>". $row->MetalSourceName ."</option>"; } sqlsrv_close( $conn); ?> </select> </form> <div id="chart_div"></div> <div id="txtHint"><b>Past metal information will be generated below.</b></div> this works fine and generates the list in the select option dropdown Script to get table contents: <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","scripts/gettabledata001.php?q="+str,true); xmlhttp.send(); } </script> this also works fine and generates the table contents based on 'q' value from the select dropdown. Google API script: <script type="text/javascript"> // Load the Visualization API and the piechart,table package. google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart()); function drawChart() { var jsonData = $.ajax({ url: "scripts/getgraphdata.php", dataType:"json", data: "q="+num, async: false }).responseText; // Instantiate and draw our pie chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, {width: 400, height: 240}); } </script> getgraphdata.php script: $q = intval($_GET['q']); ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); $query ="SELECT TOP(30) tblMetalPrice.MetalSourceID, tblMetalPrice.DateCreated, tblMetalPrice.UnitPrice, tblMetalPrice.HighUnitPrice, tblMetalSource.MetalSourceName FROM tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID WHERE tblMetalPrice.MetalSourceID = '".$q."' ORDER BY tblMetalPrice.DateCreated DESC"; $result = sqlsrv_query($conn, $query); echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"Unit Price\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ "; $total_rows = sqlsrv_num_rows($result); $row_num = 0; while($row = sqlsrv_fetch_object($result)){ $row_num++; if ($row_num == $total_rows){ echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}"; } else { echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}, "; } } echo " ] }"; sqlsrv_close( $conn); When ever i try these they don't work the getgraphdata.php scripts runs fine the issue I believe but may be totally wrong may be done to the google api script that should generate the chart but doesn't. Can anyone help here I've been trying to sort this for a few days now and losing confidence in myself rapidly. Thanks Kris
  11. Good morning, I am trying to convert a mssql query into json format so that I can then later pass this through google's visualisation api. The query and encoding seems to be working but the encode returns NULL. I have checked the normal gotcha's of making sure its utf8 encoded and that I have used a version of PHP that has the encode (using php 5.3.19). Can any one help me with getting the encode to work. PHP CODE: <?php //connection and database details (known to be working) if( $conn ) { echo "Connection established.<br><br>"; }else{ echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } $query = "SELECT * FROM tblProducts"; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC) ); $arr = array($result); $encodedarray = array_map(utf8_encode, $arr); echo json_encode($encodedarray); sqlsrv_close( $conn); ?> When I run this code on the server it comes back with: Connection established. [null] Has anyone got any ideas of getting this to work? Thanks Kris
  12. 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? :confused: Thanks, Revathy
  13. I'm using the following function/php code to create some JSON for some NVD3 charts I am using. The problem I have is that for each KEY, the $i variable will count even and odd numbers. Here is the data below as you can see in the first line, every x:counts as 0, 2, 4 , 6. and for KEY:IDNB it counts 1,3,5,7. I need them all to count equally so that they are against the same line on my graph. How can I make them count 1,2,3,4 for both "keys" [{"key":"IDNA","values":[{"x":0,"y":387.73},{"x":2,"y":388.57},{"x":4,"y":388.04},{"x":6,"y":387.94},{"x":8,"y":388.24},{"x":10,"y":388.44},{"x":12,"y":387.99},{"x":14,"y":388.53},{"x":16,"y":388.79},{"x":18,"y":388.6},{"x":20,"y":388.55},{"x":22,"y":388.48},{"x":24,"y":388.72},{"x":26,"y":389.02},{"x":28,"y":388.59},{"x":30,"y":388.07},{"x":32,"y":388.14},{"x":34,"y":388.58},{"x":36,"y":388.12},{"x":38,"y":388.76},{"x":40,"y":388.15},{"x":42,"y":388.26},{"x":44,"y":388.09},{"x":46,"y":388.58},{"x":48,"y":386.85},{"x":50,"y":388.23},{"x":52,"y":388.16},{"x":54,"y":388.83},{"x":56,"y":388.79},{"x":58,"y":388.74},{"x":60,"y":388.78},{"x":62,"y":388.54},{"x":64,"y":388.36},{"x":66,"y":388.7},{"x":68,"y":388.54},{"x":70,"y":388.02},{"x":72,"y":388.05},{"x":74,"y":388.31},{"x":76,"y":388.65},{"x":78,"y":388.98},{"x":80,"y":387.78},{"x":82,"y":389.42},{"x":84,"y":388.86},{"x":86,"y":388.66},{"x":88,"y":388.51},{"x":90,"y":388.27},{"x":92,"y":389},{"x":94,"y":387.8},{"x":96,"y":388.18},{"x":98,"y":388.66}]},{"key":"IDNB","values":[{"x":1,"y":387.33},{"x":3,"y":388.5},{"x":5,"y":387.75},{"x":7,"y":387.98},{"x":9,"y":388.57},{"x":11,"y":388.23},{"x":13,"y":387.83},{"x":15,"y":388.31},{"x":17,"y":388.99},{"x":19,"y":388.7},{"x":21,"y":388.49},{"x":23,"y":388.21},{"x":25,"y":388.4},{"x":27,"y":389.05},{"x":29,"y":388.26},{"x":31,"y":387.88},{"x":33,"y":388.2},{"x":35,"y":388.3},{"x":37,"y":388.08},{"x":39,"y":388.29},{"x":41,"y":388.04},{"x":43,"y":387.91},{"x":45,"y":388.23},{"x":47,"y":388.47},{"x":49,"y":386.83},{"x":51,"y":387.55},{"x":53,"y":388.03},{"x":55,"y":388.98},{"x":57,"y":388.7},{"x":59,"y":388.94},{"x":61,"y":388.47},{"x":63,"y":388.5},{"x":65,"y":387.66},{"x":67,"y":388.17},{"x":69,"y":388.29},{"x":71,"y":387.73},{"x":73,"y":388},{"x":75,"y":388.36},{"x":77,"y":388.35},{"x":79,"y":388.75},{"x":81,"y":387.36},{"x":83,"y":389.32},{"x":85,"y":388.74},{"x":87,"y":388.86},{"x":89,"y":388.57},{"x":91,"y":388.21},{"x":93,"y":388.74},{"x":95,"y":387.84},{"x":97,"y":388.18},{"x":99,"y":388.7}]}] Here is the PHP im using to make the data from a query $lrs = CDB::ExecuteQuery($sql); if($lrs) { $jsonData = convert($lrs); } function convert($lrs) { $i = 0; $intermediate = array(); while ($vals = CDB::GetAssoc($lrs)) { $key = $vals['VARIABLE']; $x = $i; $y = $vals['VAR_MEASURE_1']; $intermediate[$key][] = array('x' => $x, 'y' => $y); $i++; } $output = array(); foreach($intermediate as $key => $values) { $output[] = array( "key" => $key, 'values' => $values ); } return json_encode($output, JSON_NUMERIC_CHECK); } can anyone point me in the right direction?
  14. Hi, I'm absolutely stuck with this piece of code, I've searched and searched to get it working and have failed miserably. It also doesn't help that I'm brand new to php My Json output currently looks like this [ { "key": "OWM1", "values": [ [ "x : EW", "y :4" ], [ "x : RSE", "y :3" ], [ "x : SWE", "y :2" ], [ "x : WTE", "y :1" ], [ "x : WWE", "y :1" ] ] }, { "key": "OWM2", "values": [ [ "x : EW", "y :4" ], [ "x : RSE", "y :2" ], [ "x : SWE", "y :1" ], [ "x : WTE", "y :3" ], [ "x : WWE", "y :2" ] ] } ] But I need it to look like this for the sake of NVD3 chart to be able to process it correctly. [ { "key": "OWM1", "values": [ { x : "EW", y : 4 }, { x : "RSE", y : 3 }, { x : "SWE", y : 2 } { x : "WTE", y : 1 } { x : "WWE", y : 21 } ] }, { key: "OWM2", values: [ { x : "EW", y : 4 }, { x : "RSE", y : 2 }, { x : "SWE", y : 1 } { x : "WTE", y : 3 } { x : "WWE", y : 2 } ] }] Here is my PHP code that I am producing the first output of json with. $result = mysqli_query($con,"SELECT CODE, _POS, COUNT(CODE) AS COUNT from defects WHERE FPOS IN ('OWM1','OWM2') GROUP BY POS, CODE"); if($result) { $jsonData = convert($result); } function convert($result) { $intermediate = array(); while($rows = mysqli_fetch_assoc($result)) { $key = $rows['POS']; $x = $rows['CODE']; $y = $rows['']; $intermediate[$key][] = array('x : ' .$x,'y :' . $y); } $output = array(); foreach($intermediate as $key => $values) { $output[] = array( "key" => $key, 'values' => $values ); } echo json_encode($output); } mysqli_close($con); Is there any way anyone could help me manipulate the code I have to look exactly like the second set of JSON code that is compatible with NVD3 charts? Thanks alot.
  15. This is more of a database architect question. I am building a CMS for website development. I am ready to use it for the first time on one of my clients. Now, my issue is is how to set up some or one of my table(s) for some areas that my client wants to be able to change in the admin section. In their website on the front page, I put together this nice block slider. Its 6 blocks with text, a background image and nice effects. At first it was always going to be static, which was no issue at all, but later they came to me and asked if they could be able to change words in the boxes themselves in the admin section.. Of course this can be easily done by creating a table that is associated with this home page block thing and each row in the table will correspond to one of the blocks on the home page. But I believe there might be an easier way to store this type of data without having to create another table for every feature the client wants to edit, for example they also want to be able to edit a slider on another page. The WordPress database then came into my mind and how they store most of their data as JSON. So I was then thinking of creating a table named 'modules' for examples with three columns (id, title, data). Then inside the data column store the editable fields as a JSON string object. For example a row could like like : 1, "Front Page Box Slider", {"slider-home" : [ {"data" : "value", "img_1", "value1"}, {"data" : "value", "img_2", "value2"} ]} I've been doing a bit of research on this and people have just been saying, never do this if you do want your data to be searched through, which I don't. Can anyone tell me why or why not I should do this, or maybe a better solution to my problem? Thank you
  16. I am a noob in api so please bear with me. I tried google searching for 1 hour but I can't understand anything from the results. Currently, I have an API in kimono with the given example data : { "name": "Summoners-Details", "count": 31, "frequency": "On demand", "version": 7, "newdata": false, "lastrunstatus": "success", "thisversionrun": "Tue Sep 02 2014 02:34:07 GMT+0000 (UTC)", "lastsuccess": "Tue Sep 02 2014 02:34:07 GMT+0000 (UTC)", "stats": { "retriedUrls": [], "failedUrls": [], "successful": 1, "rows": 31, "retried": 0, "failed": 0, "duration": 1894 }, "results": { "rank": [ { "division": "Wukong's Lancers Silver-tier II" } ] } } Here is the php code I am trying to use to get the division data, but I am getting nothing! : <?php $request = "https://www.kimonolabs.com/api/c6qj1oc?apikey=xxxxxxxxxxxxxxxxxx"; $response = file_get_contents($request); $results = json_decode($response, TRUE); $division = $results->{'results'}->{'rank'}->{'division'}; echo $division; ?> What am I doing wrong here??
  17. I want to print data from response json? I was debug with firebug and show this : {"umumu":"","levelu":1,"nameu":""} How to echo data array just levelu. But i don't know how to make it? thanks
  18. We are not getting the error message, that should match with the error_code We sending the code and the object contains the error/success message to show!!! This seems to almost works. It is part of Jquery Validations, once the field or submit button is clicked. It looks for error on field. then Enter the Ajax Funciton which is to parse the error code and the out put the error message which is coming from json object. The code is not returning the error message, on line (alert(data)) Produces [object,object] not actual data string. The error message does not return. Please help, is there something work with our ajax request //*new style for error Messages*/ //var jsonErrors = frontEndErrorCodes; //JC wrote. //MG added. To retrieve Front-end error codes as well as //Backend Error Codes function _getErrorMessage(errorCode, message){ var errorData = JSON.stringify({error_code: errorCode, message: message}); var dataString = $.parseJSON(errorData); $.ajax({ url: './retrieveErrorMessage.json', type: 'POST', data: dataString, dataType: "json", contentType: 'application/json', mimeType: 'application/json', success: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice ==true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, error: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice == true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, fail: function(jqXHR, textStatus) { alert(data); if(textStatus == "parsererror"){ return "We're Sorry a system error occured"; } } }); }
  19. Hi Guys and Girls, I'm having a bit of a hard time getting some pagination working. I have a script using CURL getting JSON results via a HTTP API. This is also used in a Wordpress Installation. The API call has a maximum of 50 records returned but allows pagination. What I can't seem to get right is actually getting this to work. Below is the code that I'm using: <?php //functions relating to wordpress go here: //---------------------------------------- $bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black'); //---------------------------------------- //End functions relating to wordpress // Start PetRescue PHP/API Code //---------------------------------------- // Open CuRL/JSON Stuff $ch = curl_init(); $category=$_GET['category']; $url="http://www.xxx.com.au/api/listings?token=xxxtokenxxx&group_id=xxx&species=".$category; curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: application/json', 'X-some-API-Key: xxxtokenxxx', )); $json = json_decode(curl_exec($ch), true); //Pagination stuffs if($_GET['page']) { $page=substr($_GET['page'],1); echo 'page'.$page; } // Functions relating to the Echo Code foreach($json['listings'] as $listing) { $short_personality=substr($listing['personality'],0,500); $peturl="http://xxx.org.au/pet-info/?petid=".$listing['id']; $medium_photo=$listing['photos'][0]['large_340']; $gallery_first=$listing['photos'][0]['xlarge_900']; $gender_class=strtolower($listing['gender']); $breed_class=strtolower($listing['species']); $name=($listing['name']); $unique_gallery_name="lightbox['.$inc.']"; $inc++; foreach($listing['photos'] as $photosthumb) { $photo_thumb_large=$photosthumb["xlarge_900"]; $photo_thumb_hidden=$photosthumb["xlarge_340"]; } $rand_background = $bg_colors[array_rand($bg_colors)]; // General IF/AND/ELSE Statements to refine the Echo Output if($listing['photos'] == null) { $medium_photo="http://xxx.org.au/wp-content/themes/xxx/images/photo_coming_soon.png"; } if($listing['desexed'] == "Yes") { $desexed="yes"; } else { $desexed="no"; } if($listing['vaccinated'] == "Yes") { $vaccinated="yes"; } else { $vaccinated="no"; } if($listing['wormed'] == "Yes") { $wormed="yes"; } elseif($listing['wormed'] == "No") { $wormed="no"; } else { $wormed="no"; } if($listing['heart_worm_treated'] == "Yes") { $heart_worm_tested="yes"; } elseif($listing['heart_worm_treated'] == "No") { $heart_worm_tested="no"; } else { $heart_worm_tested="no"; } if($listing['species'] == "Dog") { $adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-dogs/?dog_name=$name"; $hwt="list-$heart_worm_tested"; } elseif($listing['species'] == "Cat") { $adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-cats/?cat_name=$name"; $hwt="list-hwt-hidden"; } // Echo the output echo'<div class="animal"> <div class="animal-image"> <a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$gallery_first.'"> <img src="'.$medium_photo.'" class="image-with-border" alt=""> <div class="border" style="width: 340px; height: 340px;"> <div class="open"></div> </div> </a> <div class="item-title-bg '.$rand_background.'"> <h2 class="entry-title"> '.$listing['name'].'</h2> <div class="animal-adopt-button"> <a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium"> Enquire about '.$name.'</a> </div> </div> </div> <div class="animal-thumbnail hidden"> <a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'"> <img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" > </a> </div> <div class="animal-content"> <div class="animal-left"> <ul class="animal-list"> <li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li> <li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li> <li class="list-age">'.$listing['age'].'</li> <li class="list-fee">'.$listing['adoption_fee'].'</li> </ul> </div> <div class="animal-right"> <ul class="animal-list"> <li class="list-'.$desexed.'">Desexed?</li> <li class="list-'.$vaccinated.'">Vaccinated?</li> <li class="list-'.$wormed.'">Wormed?</li> <li class="'.$hwt.'">Heart Worm Tested?</li> </ul> </div> <div class="animal-full"> <ul class="animal-list"> <li class="list-description">'.$listing['personality'].'</li> </ul> </div></div> <div class="clearer"></div> </div> <div class="delimiter"></div>'; // Close the CURL } echo' <div class="pagination footer-pagination"> <nav class="pagination"> <div class="pages">'; for($i=1;$i<=$json['total_pages'];$i++) { $this_page=substr($_GET['page'],1); $active=""; if($i==$this_page) { $active="active"; } echo ' <span class="page'. $active.'"> <span class="number"> <a rel="prev" href="http://xxx.org.au/pet/?category=dog&page='.$i.'"> '.$i.'</a> </span> </span> </div> </nav> </div>'; curl_close($ch); } ?> This is a sample of the JSON results: {"listings":[{"adoption_fee":"$200 ","adoption_process":"For cats, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-cats/\">Pre-Adoption Questionnaire - Cats</a>.\r\n\r\nFor dogs, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-dogs/\">Pre-Adoption Questionnaire - Dogs</a>.\r\n\r\nFor more information on our Adoption Process, please visit this <a href=\"http://xxx.au/our-adoption-process/\">link</a>.\r\n\r\nPlease make sure that you are familiar with our <a href=\"http://xxx.org.au/adoption-agreement/\">Adoption Agreement</a> as it has recently changed.\r\n\r\nFor more information on any of our animals, please <a href=\"http://xxx.org.au/contact-us/\">Contact Us</a>.","age":"2 years 5 months","breeds":["Domestic Long Hair"],"breeds_display":"Domestic Long Hair","coat":"Long","contact_name":null,"contact_number":null,"contact_preferred_method":"Email","created_at":"30/1/2014 21:36","date_of_birth":"20/2/2012","desexed":true,"foster_needed":false,"gender":"Female","group":"xxx","heart_worm_treated":null,"id":273191,"interstate":false,"last_updated":"5/8/2014 12:20","medical_notes":"","microchip_number":"","mix":false,"multiple_animals":false,"name":"Helena HC13-394","personality":"Stunning Helena!\r\n\r\nThis beautiful girl is looking for a home that is fairly relaxed. She is not happy about sharing her current foster home with some bossy cats, she likes to be the princess of her realm.\r\n\r\nShe is very affectionate, and when it is quiet she will come and have a big smooch around our legs, and purr her pretty little purr. \r\n\r\nShe is somewhat timid to start with, but enjoys the company of people and once she trusts, she's a very special companion.\r\n\r\n","photos":[{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_70x70_96020.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_130x130_96020.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_340x340_96020.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_900x900_96020.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_70x70_d2d41.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_130x130_d2d41.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_340x340_d2d41.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_900x900_d2d41.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_70x70_982c6.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_130x130_982c6.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_340x340_982c6.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_900x900_982c6.jpg"}],"senior":false,"size":null,"species":"Cat","state":"WA","vaccinated":"Yes","wormed":"Yes"}, And the pagination details are at the bottom of the JSON response: "page":"1","per_page":"50","total_pages":"6" The issue I get with all of this, is when calling the PHP file again, it's just returning the first page of results and not the second page. Any help would stop me from eating my own eyeballs, as I've been staring at this for hours! Cheers, Dave
  20. Hi ! I am having a heck of a time sending data back in responseText. First of all, I am not actually sure how my data is being sent back into responseText - it is the result of me using a jquery plugin called iframetransport which seeks to transport file inputs across an iframe for ajax like form submission. Anyway, I am echoing back data from PHP like so echo json_encode(array("rowData"=> '<div class = "row" data-id = "'.$row['id'].'" > <div class = "row"><img src="data:image/jpeg;base64,'.base64_encode( $row['blob'] ).'"/></div> <div class = "container"> <div class = "name"><p>'.$row['name'] .'</p></div> </div> </div>')); I know that this data is valid in normal ajax $.posts because I also have form submission without the iframetransport, and it returns the exact same data with no issue. However, when the above data makes its way into responseText it looks like this on the client side: "{"rowData":"\n\t\t\t\t\t<\/div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tasdasd<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t\t1<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>"}" All my divs and elements are replaced with \t or they are not making it into the response. Also when I return blobs like this (this is even worse) I get a 414 (Request-URI Too Large) Any help is appreciated. This is the plugin http://cmlenz.github.io/jquery-iframe-transport/ if interested.
  21. Hi, I am having troubles trying to add View/Edit/Del options to my web system modules. I am not the creator of the web system so it's complicated for me, also, I am a newbie on this. I want to be able to view/edit/del from admin panel every product or client stored in my db. Here's the Clients module code: client.html <div ng-include="'views/menu.html'"> </div> <button type="button" class="btn btn-primary" ng-model = 'newProduct' ng-click = 'newProductButton()'>{{buttonName}}</button> <hr> <div class="table-responsive" ng-show ='!newProduct'> <table class="table table-striped table-hover"> <tr> <td>Nº</td> <td>Cédula</td> <td>Nombre</td> <td>Apellido</td> <td>Dirección</td> <td>Email</td> <td>Télefono</td> </tr> <tr ng-repeat= 'client in clients track by $index'> <td>{{$index + 1}}</td> <td>{{client.codigo}}</td> <td>{{client.nombre}}</td> <td>{{client.apellido}}</td> <td>{{client.direccion}}</td> <td>{{client.email}}</td> <td>{{client.telefono}}</td> </tr> </table> </div> <div ng-show = 'newProduct'> <form role="form" ng-submit ="updateClient (id,name,lastName,address,phoneNumber,email)"> <label>Cédula</label> <div class="form-group"> <input class="form-control" placeholder="Cédula" ng-model='id' id="id"> </div> <label>Nombre</label> <div class="form-group"> <input class="form-control" placeholder="Nombre" ng-model='name' id="sname"> </div> <label>Apellido</label> <div class="form-group"> <input class="form-control" placeholder="Apellido" ng-model='lastName' id="lastName"> </div> <label>Dirección</label> <div class="form-group"> <input class="form-control" placeholder="Dirección" ng-model='address' id="address"> </div> <label>Teléfono</label> <div class="form-group"> <input type='tel' class="form-control" placeholder="Teléfono" ng-model='phoneNumber' id="phoneNumber"> </div> <label>Email</label> <div class="form-group"> <input type='email'class="form-control" placeholder="Email" ng-model='email' id="email"> </div> <div class="alert alert-success" id='alertSuccess' style="display:none">Ingresado Satisfactoriamente...</div> <div class="alert alert-danger" id='alertDanger' style="display:none">Ese cliente ya fue agregado</div> <button type="submit" class="btn btn-primary">Agregar Cliente</button> </form> </div> client.js 'use strict'; /** * @ngdoc function * @name belkitaerpApp.controller:ClientCtrl * @description * # ClientCtrl * Controller of the belkitaerpApp */ angular.module('belkitaerpApp') .controller('ClientCtrl', function ($scope,$http) { $scope.newProduct = false; if($scope.newProduct){ $scope.buttonName = 'Ver Tabla'; } else{ $scope.buttonName = 'Ingresar Cliente'; } $http.get('../serverSide/clients.php').success(function(clients){ console.log(clients); $scope.clients = clients.Clients; }) $scope.newProductButton = function(){ $scope.newProduct = !$scope.newProduct; if($scope.newProduct){ $scope.buttonName = 'Ver Tabla'; } else{ $scope.buttonName = 'Ingresar Cliente'; } } $scope.updateClient = function(id,name,lastName,address,phoneNumber,email){ $http.post('../serverSide/updateClient.php',{id:id,name:name,lastName:lastName,address:address,phoneNumber:phoneNumber,email:email}).success(function(data){ console.log(data); $('#alertSuccess').show("slow"); setTimeout(function() { $('#alertSuccess').hide('slow'); }, 3000); }).error(function(data){ console.log(data); $('<div id="alertDanger"></div>').show("slow"); setTimeout(function() { $('<div id="alertDanger"></div>').hide('slow'); }, 3000); }) } }); client.php <?php require_once 'database.php'; $db = new Database(); $clients = $db->queryAll('SELECT clie_id as id,clie_cod as codigo, clie_ape as apellido, clie_nom as nombre, clie_dir as direccion, clie_ema as email, clie_tel as telefono FROM cliente','Clients'); echo json_encode($clients); ?> I have found a php code on the web and I was wondering if it was possible to merge it with my existing one. I tested the code with my db and it's working but I do not know how to merge it with my existing code. Here's the code: <?php if (isset($_POST['submit'])) { include 'db.php'; $clie_cod=$_POST['clie_cod'] ; $clie_ape= $_POST['clie_ape'] ; $clie_nom=$_POST['clie_nom'] ; $clie_dir=$_POST['clie_dir'] ; mysql_query("INSERT INTO `cliente`(Código,Apellido,Nombre,Dirección) VALUES ('$clie_cod','$clie_ape','$clie_nom','$clie_dir')"); } ?> </form> <table border="1"> <?php include("db.php"); $result=mysql_query("SELECT * FROM cliente"); while($test = mysql_fetch_array($result)) { $id = $test['clie_id']; echo "<tr align='center'>"; echo"<td><font color='black'>" .$test['clie_id']."</font></td>"; echo"<td><font color='black'>" .$test['clie_cod']."</font></td>"; echo"<td><font color='black'>". $test['clie_ape']. "</font></td>"; echo"<td><font color='black'>". $test['clie_nom']. "</font></td>"; echo"<td><font color='black'>". $test['clie_dir']. "</font></td>"; echo"<td> <a href ='view.php?clie_id=$id'>Edit</a>"; echo"<td> <a href ='del.php?clie_id=$id'><center>Delete</center></a>"; echo "</tr>"; } mysql_close($conn); ?> </table> </body> </html> Any help would be highly appreciated. Thank you very much.
  22. Hello guys, first post here. I have a web system which contains a login form programmed in 3 different languages HTML, PHP and JS. The problem is that it's not working, you can access without entering any data, you just press enter and it will work, I don't know why it is not validating any credentials. I was thinking about some query problems but I don't know. I am a newbie on this. I have read a lot but haven't found an answer. A friend helped me build the system but left that uncompleted and he's nowhere to be found. I was wondering if you could help me out with this. <form role="form" ng-submit="login(user,password)"> <div class="form-group"> <input type="user" class="form-control" ng-model='user' placeholder="Usuario"> </div> <div class="form-group"> <input type="password" class="form-control" ng-model='password' placeholder="Contraseña"> </div> <div class="alert alert-warning" id='alert' style="display:none">Revise la informacion...</div> <div class="alert alert-danger" style="display:none" id='alertErr'>Error Usuario o Contraseña Erronea intentelo de nuevo</div> <button type="submit" class="btn btn-primary">Ingresar</button> </form> <?php require_once 'database.php'; $db = new Database(); $body = json_decode(file_get_contents('php://input')); $user =$db->query("SELECT * FROM usuario WHERE usua_login = '".$body->user."' AND usua_pass = '".$body->password."'"); if($user == false){ http_response_code(404); } else{ http_response_code(200); echo json_encode($user); } ?> 'use strict'; /** * @ngdoc function * @name belkitaerpApp.controller:MainCtrl * @description * # MainCtrl * Controller of the belkitaerpApp */ angular.module('belkitaerpApp') .controller('MainCtrl', function ($scope,$http,$location) { $scope.login = function(user,password){ console.log('Login...'); if(user =='' || password ==''){ $('#alert').show("slow"); setTimeout(function() { $('#alert').hide('slow'); }, 3000); } else{ $http.post('../serverSide/login.php',{user:user,password:password}).success(function(data){ console.log('OK!'); $location.path('/products'); }).error(function(data){ $('#alertErr').show("slow"); setTimeout(function() { $('#alertErr').hide('slow'); }, 3000); }); } } });
  23. Hi everyone. I am looking at creating my application's back end with PHP, which returns all data with Jason or simplexml. I have tried Slim once, but think there should be something easier to use. Can anyone give me suggestions on what I can use which is easy to catch on, and maybe an example? Appreciate it. Kind regards
  24. I really don't understand the point of an API. I am totally lost on this one. I have never in my life used JSON and barely touched Javascript so I'm already quite behind the curve but this was my understanding of the "purpose" of an API; You have some data in a database that others might find useful so you write a script that allows people to go in and pull data from it. So why aren't these APIs just built using PHP? If I have a database table of first names, last names and email-addresses, and for some reason I want other people on the internet to be able to get at that, then why don't I just write a one-page script that list them all out? Then all the user has to do is "include" it in their code, right? That's probably really over-simplistic, and I am surely missing the point. There must be a point, but I cannot find a single source anywhere with an actual decent explanation of this. What am I missing? You never know, perhaps you're all about to tell me that most APIs are built using PHP and what I've described is pretty much it. But everything I research leads to a dead end because they all refer to one another; Example 1 - "Oh JSON is freaking awesome. I use it because it's awesome. It's awesome for work working with APIs". Example 2 - "Oh, APIs, yeah, you totally have to have APIs. All you have to do is use JSON. It's awesome". Not direct quotes, but close enough! Seriously, help me out. I have a lot of public data on my server and I am positive that someone can make good use of it. But how?
  25. I have created a flashcard program to teach Japanese vocabulary. I want to add sound files from native speakers so I have created a page with a recorder that 1. displays a word (on load) 2. allows the native speaker to record the word (on press of a button) 3. uploads the recording to the server (on press of another button) I wrote the word display as a separate php script so that I could use Ajax to just change the word being recorded, so that I would not need to reload the entire page every time the speaker switched to a new word. The js that gets the word to be recorded is: function ajaxRequest(){ //declare the variable at the top, even though it will be null at first var req = null; //modern browsers req = new XMLHttpRequest(); //setup the readystatechange listener req.onreadystatechange = function(){ //right now we only care about a successful and complete response if (req.readyState === 4 && req.status === 200){ //inject the returned HTML into the DOM document.getElementById('cardData').innerHTML = req.responseText; }; }; //open the XMLHttpRequest connection req.open("GET","nextcard.php",true); //send the XMLHttpRequest request (nothing has actually been sent until this very line) req.send(); }; The section that uploads the file is: $('#send').click(function(){ $.jRecorder.sendData(); } and it gets the filename from another script: $.jRecorder( { host : 'http://localhost:10088/NewFolder/japanese/jrecorder/acceptfile.php?filename=hello.wav' The problem that I have is that when I get each word I want to change the name of the file being uploaded. It all works and if I reloaded the page each time I could do this: $.jRecorder( { host : 'http://localhost:10088/NewFolder/japanese/jrecorder/acceptfile.php?filename=<?php echo $word.'_'.$reader_id;?>.wav' but I want to stay on the Ajax path. So, I think that I need to convert the newcard program to return json with something like: $response=array(filename=>$word.$reader_id, card_data=>$card_stuff); echo json_encode($response); but once I get the json back I don't see how I get the filename into the script that sets the upload url and make that script re-execute. Is there a reasonable way to do that?
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.