PHP - Item Count At 1 When No Items Being Returned
I have a class that I use to do my db queries. I'm starting to work on a new project and purposely put in a query which would fail, thus returning no results, just to make sure the error trapping is working. Here's my code:
Code: [Select] function getResults($query) { $results = mysql_query($query) or die (mysql_error() . "\n\nYour request couldn't be procesed.<p>" . $query); $itemcount = count($results); if ($itemcount > 0) { $i=0; while($itemcount > $i) { $i++; $userdata = array('queryresult' => '!success', 'displayName' => mysql_result($results, $i-1, 'displayName'), 'title' => mysql_result($results, $i-1, 'title')); } } else { $userdata = array('queryresult' => '!fail'); } return $userdata; } when I print $itemcount it returns a value of 1, which forces the conditional and an attempt at parsing the results array. However, in my browser I get these error messages: 1 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 4 in /Library/WebServer/Dev/timesheet/lib/mysqlconnect.php on line 29 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 4 in /Library/WebServer/Dev/timesheet/lib/mysqlconnect.php on line 29 It seems as if it is telling me that results has both 1 and no items. Am I doing something to cause this? Similar TutorialsI would like to add another count that after every 4 items, it loops and create a added piece of script, by adding <ul><li> tags after every 4 items. I want to addthis piece of code, every fours items after it close </div> Code: [Select] <ul> <li> <div class="box"> <!--All fields and information here--> </div> <div class="h2"></div> <div class="box"> <!--All fields and information here--> </div> <div class="h2"></div> <div class="box"> <!--All fields and information here--> </div> <div class="h2"></div> <div class="box"> <!--All fields and information here--> </div> <div class="h2"></div> </li> </ul> I currently have this piece of code, which builds a list per every <div class="box">, then closes the item </div> and start another one as same. SEE current CODE. Code: [Select] <?php $dealList = $this->dealList; if(count($dealList)==0) echo '<h3>'.JText::_('NO_DEAL_MESSAGE').'</h3>'; $count = 1; foreach ( $dealList as $row): $link = 'index.php?xxx=' . $row->id; if(!Helper::is_urlEncoded($row->pic_dir)) { $imageUrl = $row->pic_dir; } else { $imageUrlArr= unserialize(urldecode($row->pic_dir)); $imageUrl = str_replace("\\","/",$imageUrlArr[0]); } ?> <div class="box"> information fields here </div> <?php if ($count%2==1){?> <div class="h2"></div> <?php } else if($count%2==0){?> <div class="h3"></div> <?php }$count++ ; endforeach;?> How do I added the Additonal count for efter four items <div class=box"> it places and start over with Code: [Select] <ul> <li> <div class="box"> information fields </div> </li> </ul> I have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! I have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that Hi guys, I need your help. I am trying to insert the rows in the mysql database as I input the values in the url bar which it would be like this: Code: [Select] www.mysite.com/testupdate.php?user=tester&pass=test&user1=tester&email=me@shitmail.com&ip=myisp However i have got a error which i don't know how to fix it. Error: Column count doesn't match value count at row 1 <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbusername'); define('DB_PASSWORD', 'mydbpassword'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $password = clean($_GET['pass']); $adduser = clean($_GET['user1']); $email = clean($_GET['email']); $IP = clean($_GET['ip']); if($username == '') { $errmsg_arr[] = 'username is missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PASSWORD is missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $sql = "INSERT INTO `members` (`username`,`email`,`IP`) VALUES ('$adduser','$email','$IP')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } echo "The information have been updated."; } ?> Here's the name of the columns i have got in my database: Code: [Select] username IP I have input the correct columns names, so I can't correct the problem I am getting. Please can you help? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331562.0 Why am I getting this error when there are 3 Fields with 3 values? Column count doesn't match value count at row 1 Code: [Select] $sql5="INSERT INTO participants (participant_name, team_no, sport) VALUES ('".implode("','$_POST[team]'),('",$_POST['participant_name'])."','$_POST[team]','$sport')"; Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. Anyone can help me? <?php $tbl_name="menu"; $kategorije = mysql_query("SELECT * FROM $tbl_name WHERE Left(menu_name, 1) BETWEEN 'A' AND 'M' ORDER BY menu_name ASC"); if (!$kategorije) { die("Database query failed: " . mysql_error()); } while ($row=mysql_fetch_array( $kategorije )) { echo "<div id=lista-header><h4>{$row["menu_name"]}</h4></div>"; $id_sub=$row['id_menu']; $podkategorije = mysql_query("SELECT * FROM submenu WHERE id_menu=$id_sub ORDER BY sub_name ASC", $connection); if (!$podkategorije) { die("Database query failed: " . mysql_error()); } echo "<ul class=\"pod\">"; while ($pod=mysql_fetch_array( $podkategorije )) { echo "<li><a href=index.php?=podkate?".$pod["id_sub"]." class=black>{$pod["sub_name"]}</a><hr size=1 align=left width=100px color=#cccccc></li>"; } echo "</ul>"; } ?> In this way, I get list with categories and hes subcategories. How to count how many subcategories have each categories, and count how many articles have each categories? Example (I wanna get this kind of look): Categories name (3) subcategoriesname (2) subcategoriesname (4) subcategoriesname (7) Categories name (5) subcategoriesname (1) subcategoriesname (14) subcategoriesname (9) subcategoriesname (2) subcategoriesname ( Categories name (2) subcategoriesname (28) subcategoriesname (17) Where the numbers represent how many categories and sub-items have articles 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; } } It's been quite a while since I have coded in PHP and I am running into difficulties looping through the returned response from an API. I am pretty comfortable in my PHP skills, but for some reason I keep getting caught up trying to loop through the following... Many of the returns from the API include several more layers of Objects, the example below is about the most simplistic return from the API.
I'm sure I'm just missing something easy and any help or example code simply looping through and echoing each result would be greatly appreciated!! Ideally I would like to be able to loop through both of the scenarios below.
I did a var_dump on the response and here is what I get:
array (size=1) 'Body' => object(stdClass)[6] public 'userContext' => object(stdClass)[8] public 'convCred' => object(stdClass)[10] ... public 'valid' => boolean true public 'isPasswordExpired' => boolean false public 'cbId' => int 0083802121 public 'cnId' => int 1000545 public 'locale' => string 'en_US' (length=5) public 'tncVersion' => int 2 public 'applicationId' => string 'ECFDA1FDBC00270772870CDC1786FFED' (length=32) public 'cbConvCred' => object(stdClass)[9] ... public 'preferenceInfo' => object(stdClass)[7] ... public 'lastLoginTime' => int 1406729928 public 'loginCount' => int 282 public 'passwordRecovered' => boolean false public 'emailAddress' => string 'abc@123.com' (length=11) public 'loginName' => string 'TEST' (length=8) public 'userId' => int 15932274 public 'userType' => object(stdClass)[14] public 'userTypeId' => int 1 public 'userTypeName' => string 'normal_user' (length=11) public 'isConfirmed' => boolean falseIf I jsonencode and jsondecode the response this is what I get: object(stdClass)[13] public 'Body' => object(stdClass)[17] public 'userContext' => object(stdClass)[18] public 'convCred' => object(stdClass)[19] ... public 'valid' => boolean true public 'isPasswordExpired' => boolean false public 'cbId' => int 0083802121 public 'cnId' => int 1000545 public 'locale' => string 'en_US' (length=5) public 'tncVersion' => int 2 public 'applicationId' => string 'ECFDA1FDBC00270772870CDC1786FFED' (length=32) public 'cbConvCred' => object(stdClass)[20] ... public 'preferenceInfo' => object(stdClass)[21] ... public 'lastLoginTime' => int 1406729953 public 'loginCount' => int 283 public 'passwordRecovered' => boolean false public 'emailAddress' => string 'abc@123.com' (length=11) public 'loginName' => string 'TEST' (length=8) public 'userId' => int 15932274 public 'userType' => object(stdClass)[24] public 'userTypeId' => int 1 public 'userTypeName' => string 'normal_user' (length=11) public 'isConfirmed' => boolean false 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. So I am accessing a web service and it returns a bunch of values, I am able to grab and print the first value, but I can't figure out how to print the second value. PHP Code that works Code: [Select] <?php //Web service that works fine $client = new SoapClient("http://www.domain.com/sc001.asmx?WSDL"); $sc001 = $client->$NT(array('var1'=>$var1)); //Grab the value tag and print it from web service call and in this case prints 001 $tag = $sc001->NTResult->results->TaggedText->tag; echo $tag; ?> But how do I get it to print the second tag that equals 120? I've tried this Code: [Select] <?php $tag2 = $sc001->NTResult->taggedResults->tag; ?> and this Code: [Select] <?php $tag2 = $sc001->NTResult->taggedResults->TaggedText->tag; ?> and this Code: [Select] <?php $tag2 = $sc001->NTResult->results->TaggedText->taggedResults->TaggedText->tag; ?> But neither work. The var_dump for is sc001 is: Code: [Select] object(stdClass)#9 (1) { ["NTResult"]=> object(stdClass)#10 (2) { ["count"]=> int(1) ["results"]=> object(stdClass)#11 (1) { ["TaggedText"]=> object(stdClass)#12 (2) { ["tag"]=> string(3) "001" ["taggedResults"]=> object(stdClass)#13 (1) { ["TaggedText"]=> array(27) { [0]=> object(stdClass)#14 (2) { ["tag"]=> string(4) "120" ["textArray"]=> object(stdClass)#15 (1) { ["string"]=> array(2) { [0]=> string(28) "Rocks " [1]=> string(14) "Big Rocks" } } } } } } } } } } } and the XML return from the service is: Code: [Select] <?xml version="1.0" encoding="utf-8" ?> - <TaggedTextArray xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.domain.com/sc001"> <count>1</count> - <results> - <TaggedText> <tag>001</tag> - <taggedResults> - <TaggedText> <tag>120</tag> - <textArray> <string>Rocks</string> <string>Big Rocks</string> </textArray> </TaggedText> Maybe the question is, how do you handle a SOAP returned array? I'm not sure, any help is appreciated. Thanks, sanchez 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 guys, I am working with an old script at the moment, there is one page which just will not populate the table results. I have tried running multiple debugging commands but the only one it flags is the line displaying Quote last; saying it's not a used function. If I comment out this line, no errors are produced but the results do not enter the table. Can anyone shed some light on this please, I've spent hours and hours and banging my head against a brick wall would probably be more constructive right now. Many thanks indeed for any help or advice. <?php mysql_connect("localhost", "$db_user","$db_upwd") or die ("Error - Could not connect: " . mysql_error()); mysql_select_db("$database"); $query="select host,count(*) from badc_mis_prog group by host"; $result = mysql_query($query) or die ("Error - Query: $query" . mysql_error()); $count=0; $hosts=array(); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $html_hlname=$row[0]; $html_hlname=preg_replace("/</","<",$html_hlname); $html_hlname=preg_replace("/>/",">",$html_hlname); array_push($hosts, $html_hlname,$row[1],0); $count++; } $query="select host,count(*) from badc_mis_prog where reported=1 group by host"; $result = mysql_query($query) or die ("Error - Query: $query" . mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $html_hlname=$row[0]; $html_hlname=preg_replace("/</","<",$html_hlname); $html_hlname=preg_replace("/>/",">",$html_hlname); for ($i=0; $i<($count*3); $i+=3) { if ($hosts[$i] == $html_hlname) { $hosts[($i+2)]=$row[1]; last; } } } for ($i=0 ; $i<(($count-1)*3); $i+=3){ for ($j=$i+3 ; $j<($count*3); $j+=3){ if ($hosts[($i+1)] < $hosts[($j+1)]){ $temp=array(); $temp[0]=$hosts[$i]; $temp[1]=$hosts[($i+1)]; $temp[2]=$hosts[($i+2)]; $hosts[$i]=$hosts[$j]; $hosts[($i+1)]=$hosts[($j+1)]; $hosts[($i+2)]=$hosts[($j+2)]; $hosts[$j]=$temp[0]; $hosts[($j+1)]=$temp[1]; $hosts[($j+2)]=$temp[2]; } } } print "<br><br><br><center><table border=\"1\">\n"; print "<tr><td>Host Name</td><td>Hosted</td><td>Reported</td><td>Ratio H/R</td></tr>\n"; for ($i=0; $i<($count*3); $i+=3) { if ($hosts[($i+1)]<15){ break;} printf ("<tr><td> %s </td><td> %d </td><td> %d </td><td>%.1f %%</td></tr>\n",$hosts[$i],$hosts[($i+1)],$hosts[($i+2)],(($hosts[($i+2)]/$hosts[($i+1)])*100)); } print "</table></center>\n"; ?> 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. 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 |