PHP - Format All Dates In An Array Returned From Pdo
Is their a way to format lr.submit_time in every record that is returned in the $results array without doing like a for/foreach loop? Like array_walk() or something similar? $query = " SELECT lr.*, l.make, l.model, l.part_number, l.description, pd.job_number, pd.line_item, pd.enterprise, pd.description, pd.qty AS order_qty, log.name AS user_full_name FROM leds_requests lr LEFT JOIN leds l ON l.id = lr.product_id LEFT JOIN production_data pd ON pd.id = lr.order_id LEFT JOIN login log ON log.user_id = lr.user_id WHERE lr.id IN( SELECT MAX(id) FROM leds_requests WHERE status_id = 0 GROUP BY order_id, product_id ) AND lr.id NOT IN( SELECT id FROM leds_requests WHERE lr.id = id AND status_id IN(1, 2, 3, 4) ) GROUP BY order_id, product_id, job_number "; $statement = $pdo->prepare($query); $statement->execute(); $results = $statement->fetchAll(); echo json_encode($results);
Similar TutorialsHi I have been trying to populate my data from 3 tables and display like this: DATE $acronym1 $acronym2 POSTS 1/9/2011 10 (this is no of posts) 3 POSTS 31/8/2011 20 10 and so on. the threads and user table will be similar as well. I am not able to populate the distinct dates since the dateline contains time as well. So when I try to print out the just dates(without time) , it prints with the dates repeated. it prints something like this: 1/9/2011 1 1/9/2011 1 and so on.. How can populate and print the the date and number of posts in the above format. Here is my complete code below: Code: [Select] <?php error_reporting(-1); //ini_set('display_errors',1); include("db.php"); //$thirty_days_ago = strtotime("-30 days"); $limit = strtotime("-1 month"); $sql=mysql_query(("SELECT * from new_site"),$con) or die(mysql_error()); while($row=mysql_fetch_assoc($sql)) { $include=$row['include']; $forumurl=$row['forumurl']; $url=$row['url']; $acronym=$row['acronym']; include("$include"); //echo $include."<br>"; $configdbname=$config['Database']['dbname']; $configdbconport=$config['MasterServer']['servername'].":".$config['MasterServer']['port']; $configusername=$config['MasterServer']['username']; $configpassword=$config['MasterServer']['password']; $configprefix=$config['Database']['tableprefix']; /* Connect to the required database */ $con2=mysql_connect($configdbconport, $configusername, $configpassword); if (!$con2) { die('Could not connect: ' . mysql_error()); } mysql_select_db($configdbname, $con2); $postdate=mysql_query("SELECT DISTINCT dateline,postid from post WHERE dateline >='$limit' ORDER by dateline DESC") or die(mysql_error()); while($postdate_results=mysql_fetch_assoc($postdate)) { $postdate_record=$postdate_results['dateline']; // echo $postdate."<br>"; $postdate_formatted=date('M dS Y ',$postdate_results['dateline']); $post_count=mysql_query("SELECT * from post WHERE dateline >='$postdate_record'"); while($post_count_results=mysql_fetch_assoc($post_count)) { //$postdate_formatted=date('M dS Y ',$post_dateline_results['dateline']); $posts=mysql_num_rows($post_count) or die(mysql_error()); //echo $acronym.":POSTS:".$posts."<br>"; echo '<table border="1">'; echo "<tr>"; echo "<th>Category</th>"; echo "<th>".$acronym."</th>"; echo "</tr>"; echo "<tr>"; echo "<td>POSTS:DATE:".$postdate_formatted."</td>"; echo "<td>".$posts."</td>"; echo "</tr>"; } $threaddate=mysql_query("SELECT * from thread WHERE dateline >='$limit' ORDER by dateline DESC") or die(mysql_error()); while($threaddate_results=mysql_fetch_assoc($threaddate)) { $threaddate_record=$threaddate_results['dateline']; $threaddate_formatted=date('M dS Y ',$threaddate_results['dateline']); $thread_count=mysql_query("SELECT * from thread WHERE dateline='$threaddate_record'"); while($thread_count_results=mysql_fetch_assoc($thread_count)) { $threads=mysql_num_rows($thread_count) or die(mysql_error()); //echo $acronym.":THREADS:".$threads."<br>"; echo "<tr>"; echo "<td>THREADS:DATE:".$threaddate_formatted."</td>"; echo "<td>".$threads."</td>"; echo "</tr>"; $userdate=mysql_query("SELECT * from user WHERE joindate >='$limit' ORDER by joindate DESC") or die(mysql_error()); while($userdate_results=mysql_fetch_assoc($userdate)) { $userdate_record=$userdate_results['joindate']; $userdate_formatted=date('M dS Y ',$userdate_results['joindate']); $user_count=mysql_query("SELECT * from user WHERE joindate='$userdate_record'"); while($user_count_results=mysql_fetch_assoc($user_count)) { $users=mysql_num_rows($user_count) or die(mysql_error()); //echo $acronym.":USERS REGISTERED:".$users."<br>"; echo "<tr>"; echo "<td>REGISTERED USERS::DATE:".$userdate_formatted."</td>"; echo "<td>".$users."</td>"; echo "</tr>"; } } } } } } echo "</table>"; ?> I'm trying to develop some php that will execute a MySQL query and move the results into XML. In this particular instance, only one record is expected to be returned, and that one row will contain all the customer data, such as last name, first name, address1, etc. While I can get my code to work and create the xml if I hard-code in all the keys (MySQL column names), I would like it to dynamically step through all the keys/MySQL column names so that if the db changes later (add more columns, for instance) the code generating the XML won't need to be altered. It should take the MySQL column name, create an element based on the column name, then create a text node and insert the value. Currently I'm just at the spot of testing by echoing the appropriate key/value pairs. The code is stopping after the first key/value without going through the rest of the columns. What do I need to do in order to get it to dynamically step through each column and get the key/value? Here's the relevant code: if($_POST['buscode']) {echo "buscode is: ".$_POST['buscode']."<HR>";} else {echo "ERROR WITH RETRIEVING BUSCODE<HR>";} $buscode = $_POST['buscode']; $query = "SELECT * " ."FROM customers " ."WHERE buscode = '$buscode'"; echo "Query will be: ".$query."<HR>"; $result = mysql_query($query); if($result){echo "Success retrieving data from ats_ajax.<HR>";} else{echo "Error retrieving data from ats_ajax\; MySQL error is:".mysql_error($result)."<HR>";} //////////////////////////////////////// // Let's test getting the keys and values from the array.... /////////////////////////////////////// while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "This is step ".$i."<BR>"; $key = key($row); echo "Key is: ".$key."<BR>"; echo "Value is: ".$row[$key]."<BR>"; $i++; }//close of while Hi all ! What would be the best way to identify and handle an empty array sent from JS to PHP? This rather simple looking problem has resulted in a lot of confusion to me. $_POST['myArray'] = ""; // an empty string -- this is how the empty array from JS is received in PHP
Hi, A piece of software I'm using an array is made that looks like the following: Code: [Select] [["Select","Vehicle",0.142933,[0.15,0.4,0.05,0.01]]] How would I be best parsing it so: Square brackets currently showing an array becomes an array within PHP Text strings surrounded by "quotations" lose the quotation mark when stored in the PHP array Numbers remain as values in the PHP array The arrays can become quite large, so which would be the best way to go about it? Regards, Jason Hi, A user selects week and a room to book. I put these into an array so I have now have an array of room numbers and dates. I don't want them to book seperate holidays for one accommodation, I have mangaged to stop them booking a two week stay and they an extra week. But I need a way to stop them booking two or three seperate two week holidays. So basically I need to just give an error if the dates they have selected are not consecutive. I have tried many variations of adding and subtracting 7 days and comparing that in the array using a loop based on the room ids being the same. I know the code below doesn't work but it gives an idea of how I been trying. Also assume that the array has aan accomID and date seperated by a comma. function search_break_in_consec_weeks($accomCountValidCheck, $accomID, $date){ $allConsec = false; foreach ($accomCountValidCheck as $key=>$value){ $varArray = explode(', ', $value); $varDate = $varArray[1]; $varAccomID = $varArray[0]; if($accomID == $varAccomID && date("Y-m-d", strtotime($date)) == date("Y-m-d", strtotime($varDate ."+7 days")) || date("Y-m-d", strtotime($date)) == date("Y-m-d", strtotime($varDate ."-7 days"))){ $allConsec = true; break; }else{ $allConsec = false; } } return $countStray; } foreach($accomCountValidCheck as $accomVal){ $varArray = explode(', ', $accomVal); $varAccomID = $varArray[0]; $varDate= $varArray[1]; $valReturnConsec = search_break_in_consec_weeks($accomCountValidCheck, $varAccomID, $varDate); if($valReturnConsec){echo '<b>'.$varAccomID.'</b>'. ' consec<br />';} if($valReturnConsec == false){echo $varAccomID .'not consec<br />';} } example structure of text database- mytextfile.txt 10-11201|2010/09/01|Sam|Thurston 10-11307|2010/09/04|Tony|Piper 10-11405|2010/09/11|Sarah|Smith <?php $file2 = 'mytextfile.txt'; $openedfile =fopen($file2, "r") or die("ERROR- could not open file for editing."); // flock($openedfile, LOCK_EX) or die("Error!- Could not obtain exclusive lock on the file to edit."); $hold[$record_count] = explode("|", trim(fgets($openedfile))); while(!feof($openedfile)) { $record_count++; $hold[$record_count] = explode("|", trim(fgets($openedfile))); } ?> What I need to do is loop through this and one by one- take any arrays that contain a date that is between $dateX and $dateY (which comes via a form input) and place it in a new array $matched. I am stumped. 1-Is there a way to do it inside the above while loop that I am not seeing? 2- Do I need to open the file in another manner? 2- Would it be best to now loop through $hold[$record_count] I am trying to keep the process short so as not to use up too much memory. Point me in the right direction for this one please. What is the name for this Array Format... Code: [Select] $resultsArray[] = array('questionID' => $questionID, 'question' => $question, 'answer' => $new_answer, 'DB_answer' => $old_answer, 'message' => $message[$q]); And does this have anything to do with Object-Oriented Programming?! Thanks, Debbie I have my array like so Code: [Select] $inaque = array("'$dir'"=>"'$company'"); When I run Code: [Select] print_r($inaque); It shows like Code: [Select] Array ( ['share_what_you_want'] => 'Share What You Want' ) How can I get this array to print out like Code: [Select] array ( 'share_what_you_want' => 'Share What You Want' ) Without the [ ] This is the format that is needed for this code that has already been written by somebody else. Thanks in advance Hi All, I need to subtract dates and display the number of days left. I have a 'Start' date and an 'End' date in DATETIME format in the DB. Not quite sure where to start. A simply start - end doesn't work . Start = 2011-11-01-00:00:00 End = 2011-11-30-23:59:59 Since it is now 2011-11-27, my output should equal 3. Any help is appreciated. I have a script that runs a query against a MySQL database, then, if it returns a resultset, it takes the 'freindly name from an array containg the database connections, then adds the data for the resultset. Unfortunately at the minute, it doesn't quite work the way that I want. So far I have: //get list of servers to query, and choose them one at a time for($a = 0; $a <sizeof($slaveRes_array); $a++) { $con = mysql_connect($slaveRes_array[$a]['server'], $slaveRes_array[$a]['user'], $slaveRes_array[$a]['password']); mysql_select_db($dbs, $con); //get list of MySQL Queries, and run them against the current server, one at a time for($b = 0; $b <sizeof($query_array); $b++) { $SlaveState = mysql_query($query_array[$b]['query1'], $con); // 1st Query // If there is a resultset, get data and put into array while($row = mysql_fetch_assoc($SlaveState)) { for($c = 0; $c <mysql_num_rows($SlaveState); $c++) { $slave_array[]['name'] = $slaveRes_array[$a]['database']; for($d = 0; $d <mysql_num_fields($SlaveState); $d++) { $slave_array[][mysql_field_name($SlaveState,$d)] = mysql_result($SlaveState,$c,mysql_field_name($SlaveState,$d)); }} } } // Run Query2...Query3....etc. } The problem is that at the minute it puts each field into a separate part of the array e.g. Array ( => Array ( [name] => MySQL02_5083 ) [1] => Array ( [Slave_IO_State] => Waiting for master to send event ) [2] => Array ( [Master_Host] => localhost ) [3] => Array ( [Master_User] => root ) Whereas what I am trying to achieve is more like: Array ( => Array ( [name] => MySQL02 ) [Slave_IO_State] => Waiting for master to send event ) [Master_Host] => localhost ) [Master_User] => root )... [1] => Array ( [name] => MySQL03 etc. etc. But I can't see how to achieve this? I'm currently looping on an array with this structu Categories{ CategoryName CategoryCode CategoryDescription Products{ product_info{ product_code product_type{ CountNumber ProductDescription } } prices{ "wholesale":"250", "retail":"400" } } }
I'm looping on the above array at each level, and I've declared an array so that I can put all my needed values into it $priceResult = array(); foreach($prices->categories as $category){ $categoryName = $category->category_name; $categoryCode = $category->category_code; $categoryDescription = $category->category_desc; foreach($category->products as $product){ foreach($product->product_info as $info){ $product_code = $info->product_code; foreach($info->product_type as $type){ $CountNumber = $type->CountNumber; $ProductDescription = $type->ProductDescription; } } foreach ($product->prices as $price => $amount) { $price_amount = $amount; } } } The problem I'm having is I don't know how to properly push into that new ```$priceResult``` array so that I can use PHPExcel to put it into a format with a subheader. The format I would want from the above example would be something like this
Test Category 1 | 123 | Category for Testing
Test Category 2 | 321 | New Category for Testing So basically I want to call PHPExcel on my $priceResult array in order to get that format where I can list my category info, and for each product within that category, I'd have a product row. Everything would be grouped by the category main header $build = Excel::create($name, function ($excel) use ($priceResult) { $excel->setTitle('Test Products'); UPDATE:
CategoryCode : 123 CategoryName : TestCategory CategoryDescription: For Testing Products{ 0{ Product_code : 123, CountNumber : 12, ProductDescription: Test Product, price_amount : 150.00 }, 1{ Product_code : 112, CountNumber : 32, ProductDescription: Test Product 2, price_amount : 250.00 } }
Hi guys, I am trying to do a multidates events availability calender. The script below indicates todays date by highlighting an orange colour and also indicates the start and end date of the event highlighting grey colour on the two dates (The colour are link via css classes as shown). Code: [Select] //Today's date $todaysDate = date("d/m/Y"); $dateToCompare = $daystring . '/' . $monthstring . '/' . $year; echo "<td align='center' "; if($todaysDate == $dateToCompare){ echo "class='today'"; }else{ //Compare's the event dates $sqlcount = "select event_start,event_end from b_calender where event_start ='".$dateToCompare."' AND event_end='".$dateToCompare."'"; $noOfEvent = mysql_num_rows(mysql_query($sqlcount)); if($noOfEvent >= 1){ echo "class='event'"; } } It works ok i.e. if start date = 01/01/2012 and end date = 04/01/2012 both date will be highlighted with grey colour. However I want it to also highlight grey on the dates between the 1st and 4th to show that then anydates between the 1st and 4th are not available and this is when I'm stuck. Please guys I need help. Thanks
Hello All, function convertTimeFormat($time12Hour) { // Initialized required variable to an empty string. $time24Hour = ""; // Used explode() function to break the string into an array and stored its value in $Split variable. $Split = explode(":",$time12Hour); // print_r(explode (":", $time12Hour)); => Array ( [0] => 09 [1] => 50 [2] => 08AM ) // Retrieved only "hour" from the array and stored in $Hour variable. $Hour = $Split[0]; $Split[2] = substr($Split[2],0,2); // Used stripos() function to find the position of the first occurrence of a string inside another string. if($Hour == '12' && strpos($time12Hour,"AM")!== FALSE) { // Code here } elseif(strpos($time12Hour,"PM")!== FALSE && $Hour != "12") { // code here } return $time24Hour; } $time12Hour = "09:50:08AM"; $result = convertTimeFormat($time12Hour); print_r($result); /* Input : "09:50:08AM"; Output : "21:50:08PM"; */
Hi all, I am currently making a website that has e-custom functions and a back end for the client. I want them to be able to upload images - but they need to be transparent. I do not want to leave this in the hands of the client, so I am looking at ways of using the GD library to make the change I got no issue with the png/gif type for upload/resize function since this type already transparent background but my major problems is how to deal with jpeg/jpg image type which is their background was not a transparent...so is it possible I can change/ convert to png/gif type upon successful of uploading image...so the new final image will be png/gif type with transparent background...is it doable...I am not even sure it is possible...? Thanks for any help.. When I submit the login form its not returning anything and it was working until I added in the $remember part so I'm wondering why its still not returning TRUE. Code: [Select] /** * Login user on the site. Return TRUE if login is successful * (user exists and activated, password is correct), otherwise FALSE. * * @param string * @param string * @param int * @return bool */ function login($username, $password, $remember) { $this->ci->load->model('kow_auth/users'); $user_data = $this->ci->users->get_user_by_username($username); if ($user_data) { $regenFromPostPW = $this->ci->genfunc->reGenPassHash($password, $user_data->password2); if ($regenFromPostPW == $user_data->password) { $this->ci->session->set_userdata(array( 'xtr' => 'yes', 'user_id' => $user_data->user_id, 'username' => $user_data->username, 'status' => $user_data->users_statuses_id, 'role' => $user_data->users_roles_id )); if ($remember == 1) { $timeTOexpire = time()+(60*60*24*31*2); $this->input->set_cookie('xtrcook', '1', $timeTOexpire); } else { $cookie = trim(get_cookie('xtrcook')); if ($cookie || is_numeric($cookie)) { delete_cookie('xtrcook'); } } $this->clear_login_attempts($user_data->user_id); $this->ci->users->insert_session($this->ci->session->userdata('session_id'), $this->ci->session->userdata('user_id'), $this->ci->genfunc->getRealIpAddr(), $this->ci->genfunc->getUserOS()); return TRUE; } else { $this->increase_login_attempt($user_data->user_id); } } else { return NULL; } } Hi I have a couple of phpbb forums on my web space. One is randomly throwing people off and it is getting far worse. I have traced down the issue to the IP address. Phpbb stores the IP address and session id and checks that they match. If not it throws the user out. The session ids seem to be there OK, but the IP addresses aren't. When it causes a problem the IP address seems to be returned as "::" (yes, 2 colons). I have used the following routine to try and obtain a relevant IP address and it to returns "::" Code: [Select] function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } Any ideas? All the best Keith Need some help finding out why this is returning a null result set:
The below code is giving me a result set of an integer set to "0" (the id), a "word"and "def" both set to NULL. It's failing at my "Error #2" point. var_dumps on $id, $word, and $def all give the null output. Each $category is being shown when I var_dump($category).
I know this shouldn't be the case because when I run this straight in PHPMyAdmin I get a non-null result set.
(Not sure why my indentation is not carrying over to the forum. Sorry about that.)
<?php session_start(); if(!isset($_SESSION['loopcatch']) || $_SESSION['loopcatch']==null || !is_int($_SESSION['loopcatch'])){ $_SESSION['loopcatch']=0; } if($_SESSION['loopCatch'] > 1){ //Email error die(); } require 'dbConnect.php'; $categories=array('business', 'music', 'film', 'drum'); //Pull Quotes //Query to Pull random quote $mainQuery="SELECT `r1`.`id`, `r1`.`word`, `r1`.`def` FROM `dictionary` AS `r1` JOIN (SELECT (RAND() * (SELECT MAX(`id`) FROM `dictionary`)) AS `id`) AS `r2` WHERE `r1`.`id` >= `r2`.`id` AND `category`=? AND `checked`=0 ORDER BY `r1`.`id` ASC LIMIT 1"; //prepare quotes query if($prepareQuote=mysqli_prepare($conn, $mainQuery)){ //filter through each category foreach($categories as $category){ //Bind the variable to the quotes query mysqli_stmt_bind_param($prepareQuote, "s", $category); //execute quotes statement mysqli_stmt_execute($prepareQuote); //Store quotes result set mysqli_stmt_store_result($prepareQuote); //Check how many rows are returned if(mysqli_stmt_num_rows($prepareQuote) > 0){ //Bind results to variables mysqli_stmt_bind_result($prepareQuote, $id, $word, $def); //If $id, $word, or $def is null abort and email error if(!is_null($id) && is_numeric($id) && !is_null($word) && !is_null($def)){ while($row=mysqli_stmt_fetch($prepareQuote)){ mysqli_autocommit($conn, FALSE); //Input into second table $updateQuery="UPDATE `quotes` SET `word`=?, `def`=? WHERE `category`=?"; //prepare insert query if($updateQuote=mysqli_prepare($conn, $updateQuery)){ //Bind the variables to the insert query mysqli_stmt_bind_param($updateQuote, "sss", $word, $def, $category); //execute insert statement mysqli_stmt_execute($updateQuote); //Store insert quote result set mysqli_stmt_store_result($updateQuote); //Check how many rows are returned on insert quote query if(mysqli_stmt_affected_rows($updateQuote) > 0){ //If query run sucessfully insert and update; if not rollback. //mark quote checked $checkedQuery="UPDATE `dictionary` SET `checked`=1 WHERE `id`=?"; //prepare checked query if($checkedQuote=mysqli_prepare($conn, $checkedQuery)){ mysqli_stmt_bind_param($checkedQuote, "i", $id); //execute checked statement mysqli_stmt_execute($checkedQuote); //Store checked quote result set mysqli_stmt_store_result($checkedQuote); //Check how many rows are returned on checked quote query if(mysqli_stmt_affected_rows($checkedQuote > 0)){ mysqli_commit($conn); } else{ echo 'Error #6 '; mysqli_rollback($conn); } } else{ echo 'Error #5'; //Email error die(); } } else{ echo 'Error #4'; mysqli_rollback($conn); } } else{ echo 'Error #3'; //Email error die(); } } } else{ echo 'Error #2'; //Query returned blank result set - Email Error } } else{ //If zero rows returned, uncheck rows in table for that specific category and re-run the query. $uncheckQuery="UPDATE `dictionary` SET `checked`=0 WHERE `category`=?"; if($uncheckQuotes=mysqli_prepare($conn, $uncheckQuery)){ //Bind the variable to the query mysqli_stmt_bind_param($uncheckQuotes, "s", $category); //execute statement mysqli_stmt_execute($uncheckQuotes); //Store result set mysqli_stmt_store_result($uncheckQuotes); //Check how many rows are returned if(mysqli_stmt_affected_rows($uncheckQuotes) > 0){ $_SESSION['loopCatch']++; header("Location: ./pullDailyQuotes.php"); } else{ //Email error } } } } } else{ //Email error echo 'Error #1'; die(); } ?> Edited by HDRebel88, 01 June 2014 - 08:54 PM. Am currently using this code, and actually thinking about it should split the query to an include in order to allow for other database drivers, on the chance we may decide to ditch the old MySQL. But I digress from the question. Code: [Select] include($lib."dbconfig.php"); $q = 'SELECT * FROM file WHERE this = "'.$that'"; $result = mysql_query($q); if (mysql_num_rows($result) > 0) If the query doesn't pick up a row I'm getting this error yo, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\webpages\*\*\admin.php on line 553 So what would be a better way of testing if the query was successful? Hi all, I really need some help getting values from the usps api Well not getting them but using them. I get the values but I need to extract the info to use in a form. This is the class im using Code: [Select] <?php require_once("xmlparser.php"); class USPS { var $server = "http://testing.shippingapis.com/ShippingAPITest.dll"; var $user = "****"; var $pass = "****"; var $service = ""; var $dest_zip; var $orig_zip; var $pounds; var $ounces; var $container = "None"; var $size = "REGULAR"; var $machinable; var $country = "USA"; function setServer($server) { $this->server = $server; } function setUserName($user) { $this->user = $user; } function setPass($pass) { $this->pass = $pass; } function setService($service) { /* Must be: Express, Priority, or Parcel */ $this->service = $service; } function setDestZip($sending_zip) { /* Must be 5 digit zip (No extension) */ $this->dest_zip = $sending_zip; } function setOrigZip($orig_zip) { $this->orig_zip = $orig_zip; } function setWeight($pounds, $ounces=0) { /* Must weight less than 70 lbs. */ $this->pounds = $pounds; $this->ounces = $ounces; } function setContainer($cont) { $this->container = $cont; } function setSize($size) { $this->size = $size; } function setMachinable($mach) { /* Required for Parcel Post only, set to True or False */ $this->machinable = $mach; } function setCountry($country) { $this->country = $country; } function getPrice() { if($this->country=="USA"){ // may need to urlencode xml portion $str = $this->server. "?API=RateV2&XML=<RateV2Request%20USERID=\""; $str .= $this->user . "\"%20PASSWORD=\"" . $this->pass . "\"><Package%20ID=\"0\"><Service>"; $str .= $this->service . "</Service><ZipOrigination>" . $this->orig_zip . "</ZipOrigination>"; $str .= "<ZipDestination>" . $this->dest_zip . "</ZipDestination>"; $str .= "<Pounds>" . $this->pounds . "</Pounds><Ounces>" . $this->ounces . "</Ounces>"; $str .= "<Container>" . urlencode($this->container) . "</Container><Size>" . $this->size . "</Size>"; $str .= "<Machinable>" . $this->machinable . "</Machinable></Package></RateV2Request>"; } else { $str = $this->server. "?API=IntlRate&XML=<IntlRateRequest%20USERID=\""; $str .= $this->user . "\"%20PASSWORD=\"" . $this->pass . "\"><Package%20ID=\"0\">"; $str .= "<Pounds>" . $this->pounds . "</Pounds><Ounces>" . $this->ounces . "</Ounces>"; $str .= "<MailType>Package</MailType><Country>".urlencode($this->country)."</Country></Package></IntlRateRequest>"; } $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $str); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // grab URL and pass it to the browser $ats = curl_exec($ch); // close curl resource, and free up system resources curl_close($ch); $xmlParser = new xmlparser(); $array = $xmlParser->GetXMLTree($ats); //$xmlParser->printa($array); if(count($array['ERROR'])) { // If it is error $error = new error(); $error->number = $array['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'])) { $error = new error(); $error->number = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'])){ //if it is international shipping error $error = new error($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR']); $error->number = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['RATEV2RESPONSE'])){ // if everything OK //print_r($array['RATEV2RESPONSE']); $this->zone = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ZONE'][0]['VALUE']; foreach ($array['RATEV2RESPONSE'][0]['PACKAGE'][0]['POSTAGE'] as $value){ $price = new price(); $price->mailservice = $value['MAILSERVICE'][0]['VALUE']; $price->rate = $value['RATE'][0]['VALUE']; $this->list[] = $price; } } else if (count($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['SERVICE'])) { // if it is international shipping and it is OK foreach($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['SERVICE'] as $value) { $price = new intPrice(); $price->id = $value['ATTRIBUTES']['ID']; $price->pounds = $value['POUNDS'][0]['VALUE']; $price->ounces = $value['OUNCES'][0]['VALUE']; $price->mailtype = $value['MAILTYPE'][0]['VALUE']; $price->country = $value['COUNTRY'][0]['VALUE']; $price->rate = $value['POSTAGE'][0]['VALUE']; $price->svccommitments = $value['SVCCOMMITMENTS'][0]['VALUE']; $price->svcdescription = $value['SVCDESCRIPTION'][0]['VALUE']; $price->maxdimensions = $value['MAXDIMENSIONS'][0]['VALUE']; $price->maxweight = $value['MAXWEIGHT'][0]['VALUE']; $this->list[] = $price; } } return $this; } } class error { var $number; var $source; var $description; var $helpcontext; var $helpfile; } class price { var $mailservice; var $rate; } class intPrice { var $id; var $rate; } ?> This is how Im getting the info Code: [Select] <?php require("usps.php"); $usps = new USPS; //http://production.shippingapis.com/ShippingAPI.dll //http://testing.shippingapis.com/ShippingAPITest.dll $usps->setServer("http://production.shippingapis.com/ShippingAPI.dll"); $usps->setUserName("****"); //Express, First Class, Priority, Parcel, Library, BPM, Media, or ALL $usps->setService("All"); $usps->setDestZip("21061"); $usps->setOrigZip("85284"); $usps->setWeight(4, 2); $usps->setContainer("Flat Rate Box"); $usps->setCountry("USA"); $usps->setMachinable("true"); $usps->setSize("Regular"); $price = $usps->getPrice(); print_r($price); ?>and that gives me this result Code: [Select] USPS Object ( [server] => http://production.shippingapis.com/ShippingAPI.dll [user] => **** [pass] => **** [service] => All [dest_zip] => 21061 [orig_zip] => 85284 [pounds] => 4 [ounces] => 2 [container] => Flat Rate Box [size] => Regular [machinable] => true [country] => USA [zone] => 8 [list] => Array ( [0] => price Object ( [mailservice] => Express Mail Hold For Pickup [rate] => 49.70 ) [1] => price Object ( [mailservice] => Express Mail [rate] => 49.70 ) [2] => price Object ( [mailservice] => Express Mail Flat Rate Envelope Hold For Pickup [rate] => 18.30 ) [3] => price Object ( [mailservice] => Express Mail Flat Rate Envelope [rate] => 18.30 ) [4] => price Object ( [mailservice] => Priority Mail [rate] => 18.35 ) [5] => price Object ( [mailservice] => Priority Mail Flat Rate Envelope [rate] => 4.95 ) [6] => price Object ( [mailservice] => Priority Mail Small Flat Rate Box [rate] => 5.20 ) [7] => price Object ( [mailservice] => Priority Mail Medium Flat Rate Box [rate] => 10.95 ) [8] => price Object ( [mailservice] => Priority Mail Large Flat Rate Box [rate] => 14.95 ) [9] => price Object ( [mailservice] => Parcel Post [rate] => 12.29 ) [10] => price Object ( [mailservice] => Media Mail [rate] => 4.05 ) [11] => price Object ( [mailservice] => Library Mail [rate] => 3.85 ) ) ) I would like to be able to just pull out some of the mailservice and rate portions to use them later on in the form, like say a dropdown box but I do not know how to just isolate each item. For instance turn that result into a 3 item select box with these options Express Mail - $49.70 Priority Mail - $18.35 Parcel Post - $12.29 Hope that makes sense. Any help appreciated. |