PHP - Checking To See If A Value Returned From The Database Is Blank Or Not?
Probably a silly question, but say you have a value in a mysql database that (naturally) can be either be blank or have characters in it.
If in my PHP I am doing a check to see if that returned field from the database HAS or DOES NOT HAVE a value entered in it, what is the proper way to do it? For example, you could do either of the following below (and I'm sure there are probably 10 other ways to do it as well). Is one of these quicker/more efficient than the other? I know it probably does not matter in the grand scheme of things because it's such a quick check either way, but if one way is more "proper" than the other, please let me know... Code: [Select] if ($mysqlvalue!=="") OR if (strlen($mysqlvalue>0)) OR Similar TutorialsHi. I've been doing tutorials all day on checking for blank fields and I have wrote a function to do so. For now I am only checking one field to see if it works. If I miss that field out (first name) It works great and displays the correct error message. Problem I have is if I fill in the whole form and send it I get an Inturnal server error. I will post my code to show you. can anyone see whats going wrong? I have \\ some of the code for now because I my keep it if I cant do this error check. session_start(); $validation_id = strval(time()); if(isset($_POST['submit'])) { $first_name = check_input($_POST['first_name'],"Please enter a first name"); $last_name = check_input($_POST['last_name']); $DOB = check_input($_POST['DOB']); $sex = check_input($_POST['sex']); $email = check_input($_POST['email']); $username = check_input($_POST['username']); $password = check_input($_POST['password']); $agree = check_input($_POST['agreed']); $creation_date = check_input($_POST['creation_date']); $user_type = check_input($_POST['member_type']); $access_level = check_input($_POST['access_level']); $validation = check_input($_POST['validation_id']); $club_user =check_input($_POST['user_type']); // $first_name = mysql_real_escape_string($_POST['first_name']); // $last_name = mysql_real_escape_string($_POST['last_name']); // $DOB = mysql_real_escape_string($_POST['DOB']); // $sex = mysql_real_escape_string($_POST['sex']); // $email = mysql_real_escape_string($_POST['email']); // $username = mysql_real_escape_string($_POST['username']); // $password = mysql_real_escape_string($_POST['password']); // $agree = mysql_real_escape_string($_POST['agreed']); // $creation_date = mysql_real_escape_string($_POST['creation_date']); // $user_type = mysql_real_escape_string($_POST['member_type']); // $access_level = mysql_real_escape_string($_POST['access_level']); // $validation = mysql_real_escape_string($_POST['validation_id']); // $club_user = mysql_real_escape_string($_POST['user_type']); $insert_member= "INSERT INTO Members (`first_name`,`last_name`,`DOB`,`sex`,`email`,`username`,`password`,`agree`,`creation_date`,`usertype`,`access_level`,`validationID`) VALUES ('".$first_name."','".$last_name."','".$DOB."','".$sex."','".$email."','".$username."','".$password."','".$agree."','".$creation_date."','".$user_type."','".$access_level."', '".$validation."')"; $insert_member_now= mysql_query($insert_member) or die(mysql_error()); $url = "thankyou.php?name=".$_POST['username']; header('Location: '.$url); and the form <form method="POST" name="member_accounts" id="member_accounts"> <input name="first_name" type="text" class="form_fields" value="<?php echo $_POST['first_name'];?>" size="20" /> <input name="last_name" type="text" class="form_fields" value="<?php echo $_POST['last_name'];?>" size="20" /> <input name="submit" type="submit" class="join_submit" id="submit_member" value="Create Account" /> <? function check_input($data, $problem='') { $data= trim($data); $data= stripslashes($data); $data= htmlspecialchars($data); if ($problem && strlen($data) ==0) { die($problem); } return $data; } ?> just a little confused where ( brackets go in this statement . im just wanting to to display the information differently depending on which message is returned from the database. thanks Code: [Select] if ($info['message'])="<a href=\"freindacept.php?username=$myusername\">Has sent you a friend request </a>";{ Echo "<a href='viewprofile.php?username={$info['username']}'><img src='http://datenight.netne.net/images/".$info['img'] ."' width='30' height='30''></a>".$info['from_user']." ".$info['message']; }elseif ($info['message'])="You have sent a contact request to"; Echo " .$info['message']<a href='viewprofile.php?username={$info['username']}'><img src='http://datenight.netne.net/images/".$info['img'] ."' width='30' height='30''></a>".$info['from_user']."; } } php5.2, mysql server5.02: if record exists,append random digit to end of information in rows column then add to database If user mike already exists and another mike is trying to create a user id I would like to keep the old mike record like it is, then add a new mike record, but add a unique digit to the end of the name mike before the record gets added to the database as a new row. Thank you kindly! Hello! I need to loop through a list of numbers and check if they are present in a column in a database or not. I'm having a hard time figuring out how to check the column value by value and compare to a incrementing $i value. here is my query... Code: [Select] $query2 = mysql_query("SELECT * FROM video"); $column = mysql_fetch_array($query2); echo $column2['cable_number']; this only echoes me the first ['cable_number'] in the database. i need to get every single one, and perform actions on each one as they come through. and here is my for() statement Code: [Select] for($i=100;$i<=$highest;$i++){ check if $i is in the database. if it is(do something) if it isn't(do something) } i need to use that $i each iteration and see if it's present in the 'cable_number' column in the database. then i do something and continue on with the next i$ value. The Script:
pdo_connect.php:
<?php $dsn = "mysql:host=localhost;dbname=2354"; $db = new PDO($dsn, "root", ""); ?>pdo_test.php: <?php try{ require_once("pdo_connect.php"); }catch(Exception $e){ $error = $e->getMessage(); } ?> <!DOCTYPE html> <html> <head> <title>Database Connection with PDO</title> </head> <body> <h1>Connection with PDO</h1> <?php if($db){ echo "<p>Connection successful.</p>"; }elseif(isset($error)){ echo "<p>$error</p>"; } ?> </body> </html>I have just watched a tutorial and tried out this script. The issue is that I am getting the following notice alongside with the error message: Notice: Undefined variable: db in C:\xampp\htdocs\oophp\pdo_test.php on line 18 SQLSTATE[HY000] [1049] Unknown database '2354'By the way this notice does happen in the tutorial as well. My question is: How to have this in ways, where the notice does not occur? I have an issue with some code I have. All the code works correctly apart from when submit is clicked not only does it update a the current club but it creates a blank entry in the database! I cant see whats wrong. Here is the code......... //gets $validation = $_GET['new_club']; //Querys $qGetClub = "SELECT * FROM clubs WHERE validationID = '$validation'"; $rGetClub = mysql_query($qGetClub); $Club = mysql_fetch_array($rGetClub); //Query for category by name $qGetCat = "SELECT * FROM club_category WHERE catID = ".$Club['cat'].""; $rGetCat = mysql_query($qGetCat); $CatName = mysql_fetch_array($rGetCat); //query for related sub categorys. $qGetSub = "SELECT * FROM sub_categorys WHERE catID =".$Club['cat'].""; $rSubCat = mysql_query($qGetSub); // query for groups created $Groupq = mysql_query("SELECT * FROM groups WHERE memberID = '".$User['memberID']."'"); //end of querys if(isset($_POST['insert_clubbtn1'])){ //Process data for validation $subcat = trim($_POST['subcat']); $NewSubCat = trim($_POST['NewSubCat']); //Prepare data for db insertion $subcat = mysql_real_escape_string($subcat); //find the new category //insert $result = mysql_query("UPDATE clubs SET `sub_category` = '$subcat' WHERE validationID ='$validation'") or die(mysql_error()); if ($result!=="") { $otherg = trim($_POST['other_groups']); $newg = trim($_POST['new_group']); $newg = mysql_real_escape_string($newg); //if an item other than none from the list is selected then update the club with an ID relating to the group it belongs to if ($otherg !=='None') { $groupsq = mysql_query("UPDATE `clubs` SET groupID ='$otherg' WHERE validationID ='$validation'") or die (mysql_error()); } // If none is selected then $newg must have a value so create a new group in the groups table and then on the next page I will add the group in the club table else { $groupsq = mysql_query("INSERT INTO `groups` (`memberID`, `group`, `clubID`) VALUES ('".$User['memberID']."', '$newg', '".$Club['clubID']."')")or die (mysql_error()); } } if ($NewSubCat !="") { mail("mail","New Sub Category Request","Dear Ring Master, \n\nThe club in the name of $name with a validation code of $validationID would like a new sub category called $new_cat\n\n \nTeam Arena\n\n\n\n"); } $url = "/members/create/create_clubp3.php?new_club=$validation"; header("Location: $url"); } Hey I'm trying to check a row in my database to see if its empty but this isnt working $usercheck = mysql_query("SELECT pet FROM users where name='$user'"); $returned_rows = mysql_num_rows($usercheck); if ($returned_rows == 0){ // do stuff if no pet }else{ echo 'There was ' . $returned_rows . ' records found.'; } The problem is its not checking the row pet its just checking to see if anything exists my database has id name pet 1 joe <empty> its just seeing joe and echoing "there was 1 record found" instead of seeing that the row pet is empty. thanks for the help Ok guys, I am working on my code as I am checking the row in a database that if i have got a same row that I insert the functions in the URL then throw the error that says "you can't store". When I am checking as the rows have already exist, i keep getting "you can now store". Do you know how i can check in a database to see if the rows is exist? here's the code: Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); 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)); } $image = clean($_GET['image']); $strings = clean($_GET['strings']); $username = clean($_GET['user']); $password = clean($_GET['pass']); if (isset($_GET['user']) && (isset($_GET['pass']))) { if($username == '' || $password == '') { $errmsg_arr[] = 'username or password are missing'; $errflag = true; } } if (isset($_GET['image']) || (isset($_GET['strings'])) || (isset($_GET['user']))) { if($image == '' || $strings == '' || $username == '') { $errmsg_arr[] = 'image, strings or username are missing'; $errflag = true; } } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['image'])) { $insert[] = 'image = \'' . clean($_GET['image']) . '\''; } if(isset($_GET['user'])) { $insert[] = 'user = \'' . clean($_GET['user']) .'\''; } if(isset($_GET['pass'])) { $insert[] = 'pass = \'' . clean($_GET['pass']) . '\''; if (count($insert)>0) { $names = implode(',',$insert); if($image && $strings && $from && $username) { $qry="SELECT * FROM members WHERE username='$username'"; $result=mysql_query($qry) or die('Error:<br />' . $qry . '<br />' . mysql_error()); $row=mysql_fetch_assoc($result); if ($row >= 1) { echo 'you cant store.'; } else { echo 'you can now store'; } } elseif($username && $pass) { echo "working 2"; } } } ?> Hello, I am trying to get this backlink checker that checks to make sure another website has my link on their website, so far I can check to make sure the "href" link is there and is correct, but I cant get the textContent to prove valid or not it seems to always be proving true even when the textConent is not in the mysql database. The other persons website will have this: <a href="http://businessinvestingsorce.com">Business Investing Source</a> I need to make sure Business Investing Source (the textContent) matches the anchor in the database. Here is my code: Code: [Select] <?php function CheckForAnchorMatch($anchortext) { $query = mysql_query("SELECT * FROM allowed_anchor WHERE anchor='$anchortext'"); if(mysql_num_rows($query) != 0) { return true; } return false; } function CheckForTargetUrl($links, $target) { foreach ($links as $link) { if (strpos($link, $target) !== false) { return true; } } return false; } function ExtractHrefLinks($html) { $dom = new DOMDocument; $linkUrls = array(); @$dom->loadHTML($html); $links = $dom->getElementsByTagName('a'); foreach ($links as $link){ $linkUrls[] = $link->getAttribute('href'); } return $linkUrls; } function ExtractAnchorText($html) { $dom = new DOMDocument; $AnchorTexts = array(); @$dom->loadHTML($html); $links = $dom->getElementsByTagName('a'); foreach ($links as $link){ $AnchorTexts[] = $link->textContent; } return $AnchorTexts; } function backlink_check($contenturl){ $url = 'businessinvestingsource.com'; $source = $contenturl; $falseFound = false; $html = file_get_contents ( $source ); $links = ExtractHrefLinks($html); if (CheckForTargetUrl($links, $url) === false) { $falseFound = "true"; $reportArray[$source] = 0; } else { $falseFound = "false"; } $html = file_get_contents ( $source ); $anchortext = ExtractAnchorText($html); if (CheckForAnchorMatch($anchortext) === false) { $falseFound = true; } else { $falseFound = false; } return $falseFound; } ?> Help greatly appreciated Is there an alert method for the MySQL database or something similar?
What is the proper way to check if the MySQL database connection is working?
I mean other than "creating" and "retrieving" with "insert" and "select".
Hey all. I'm a noob so bare with me. Just started studying php and have an assignment due. At this phase of the project I have to create a form where a user can register data and I should retrieve that data and store it in my database. Now I have already created the form (student_reg.php) and a separate file with php code (demo.php) My database is name "registration" and I am trying to put this info in the "student" table. It has about 15 fields but for now I am only trying trying to insert the 1 field of data to test if it works. Dont know if that may cause problems? So far my demo.php connects to the database successfully. The problem I am having is the information I submit does not showing in the database field. However, I have an id field in my case a student number field which is set to auto increment so it automatically updates (1,2,3,4) with each new sumbitted info. When I submit the info the id field gets updated each time with a new row ( so i assume some information is somehow going through ) however the info I entered will remain blank in its field. :banghead: Heres my form (student_reg.php) Code: [Select] <div id="apdiv3"> <FORM action = "demo.php" method ="post "> <p>Course name:</p> <INPUT TYPE = "text" name="input"/> <INPUT TYPE = "Submit" VALUE = "Submit"/> </div> </FORM> and heres my php code to retrieve the form info Code: [Select] <?PHP include 'includes/config.php'; //connect to database $link=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //error check if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected=mysql_select_db(DB_NAME, $link); // error check if (!$db_selected) { die('can\t use ' . DB_NAME . ': ' . mysql_error()); } // Connected to database // retrieve form data $value=(isset($_POST['input'])); $sql = "INSERT INTO student (sname) VALUES ('$value')"; if (!mysql_query($sql)) { die ('Error: ' . mysql_error()); } mysql_close(); ?> I also recieved a notice "undefined index" or something like that from this part of the code "$value=(isset($_POST['input']));" before I inserted "isset" to the code. I'm not sure if what I did fixed the problem or only hid it, or whether that notice was related to the problem I'm having of not retrieving the info. Haha sorry guys know this is probably childs play for you but I just started out and really need to fix this so I can catch up with this project. Feel free to add tips and comments on other areas. Thanks :mrgreen: hi all i am having a big problem that i have been trying to find out what is going on for weeks. i have a echo script that echos data that is in my database, and if i have to refresh the page it will add blank data in my database and the top echo info is blank as well. how can i fix this, and i was wanting to know how do i echo out my info in a textarea. i added a jepg to show you what i mean. here is my code echoforms.php <?php error_reporting(0); require_once('demo.php'); /*Open the connection to our database use the info from the config file.*/ $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); $sql = "SELECT company_name, contact_name, address, street_number, postcode, contact_number, contact_email, budget, description FROM 3dartactforms"; $results = mysql_query($sql); if (!$results) { die('Invalid query: ' . mysql_error()); } while($result = mysql_fetch_array( $results )){ echo '<div style="border: 1px solid #e4e4e4; padding: 15px; margin-bottom: 10px;">'; echo date("d/m/y"); echo '<p>Company Name: ' . $_POST['company_name'] . '</p>'; echo '<p>Contact Name: ' . $_POST['contact_name'] . '</p>'; echo '<p>Address: ' . $_POST['address'] . '</p>'; echo '<p>Street Number: ' . $_POST['street_number'] . '</p>'; echo '<p>Postcode: ' . $_POST['postcode'] . '</p>'; echo '<p>Contact Number: ' . $_POST['contact_number'] . '</p>'; echo '<p>Contact Email: ' . $_POST['contact_email'] . '</p>'; echo '<p>Budget: ' . $_POST['budget'] . '</p>'; echo '<p>Description: ' . $_POST['description'] . '</p>'; echo '</div>'; } ?> I have 2 files; Newfault.php and thankyou.php 1) Data is entered into a form in Newfault.php 2) The data from this form is retieved in thankyou.php and is then inserted into a table called "Calls" Problem: My entered record is being added to my database OK, but it is also adding a blank record for some reason and I can't work out why. Can anyone help? This is for my uni assignment. Thanks, Ladykudos Hi there, I am using this code to send the users email address to the database. That works fine, but i keep getting blank info added to the database. Does anyone know how i can stop this? <?php $con = mysql_connect("*","*","*"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Thanks, 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; } } 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 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. 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 |