Jump to content

Search the Community

Showing results for tags 'array'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

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

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I have been trying to finish up a website for a while now and I can't seem to figure out how to do this. Right now I want one out of four pictures to randomly be selected and presented on a webpage. I have already achieved this through the shuffle() function. However, I want the name of whichever picture shows up to be recorded in my MySQL database. How do I go about doing this? I searched online and came across the function serialize(), but then I was advised not to use it since I only wanted the name of one of the pictures in the array instead of all of them. Does anyone have any functions/sample code that may be of use? (Example in case I didn't explain clearly: I have four pictures: a.ipg, b.jpg, cjpg, d.jpg Let's say the shuffle() function choses b.jpg to be displayed on the webpage. How could I get b.jpg to be sent to my database?) Thank you.
  2. Hi there, I've posted this at stackoverflow but did not receive any replies so far so I'd like to try here as well. ------ I have an array of variable dimensions and namings. Sometimes associative, sometimes partially. Sometimes just a single array, sometimes multiple dimensions. An example array is this: array(4) { ["name"]=> string(9) "Some Name" ["user"]=> array(2) { ["id"]=> int(1) ["msgs"]=> array(3) { [0]=> string(16) "My first message" [1]=> string(17) "My second message" ["folder"]=> array(2) { ["first"]=> string(13) "Some folder.." [1]=> string(17) "some other stuf.." } } } [0]=> string(17) "More random stuff" ["foo"]=> array(2) { [0]=> string(10) "more stuff" ["bar"]=> string(7) "The end" } } I would like to have a function that goes through every key and value pair and performs a function, without altering the structure of the array. In this case, I want to apply htmlspecialchars() with ENT_QUOTES on every key and value pair in the array while keeping the array itself intact structure wise. I have tried with array_walk_recursive and array_map, neither seem to do the trick. I'm pretty new to PHP but I tried the following function by messing about with how I think it should be done but it's obviously not working private function CreateErrorArray($array, $knownKeys=NULL) { if (is_array($array)) { foreach ($array as $key => $value) { if (is_array($value)) { if (is_null($knownKeys)) { $keys = array($key); $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$key], $keys); } else { $keys = array_push($knownKeys, $key); $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$knownKeys][$key], $keys); } } else { $this->response['ERRORARRAY'][$key] = $value; } } } }
  3. Hello, i have the following code: php 5, ms server 2008, iis 7 I pass this script a csv list of file paths like so... ,C:\path\path\path\file.name,C:\path\path\anotherFile.name,C:\path\path\path\file3.file (yes there is a leading comma in the string for some reason..) $files = $_POST['files']; $files = explode(',', $files) foreach($files as $filename){ if(file_exists($filename)){ echo '":' . $filename .':"Does Exist<br />'; } else { echo 'Sorry ":' . $filename . ':" Does Not Exist<br />'; } } My problem: the first file path shows it exists and there is no white space in the string, all the file paths after the first one show like such: ":C:\path\path\path\file.name:" Does Exist // 1st path (good) ": C:\path\path\anotherFile.name :" Does Not Exist ": C:\path\path\file3.file:" Does Not Exist pleas note... i put the ": and :" in there to show that there is indeed a white space character in front of and behind the filepaths. EXCEPT for the last path.. there is no trailing white space there. Please explain why you think the white space is being added to these and what i can do to get rid of it. thanks, dogdaynoon
  4. Hello Guys, I have a database that is set up something like this: Name Type_a Type_b 3 series Car BMW 1 series Car BMW A class Car Merc C class Car Merc 500 Motorbike XYZ 600 Motorbike XYZ I want to pull this info out of my database and display it like this: Cars: BMW: 1 Series 3 Series Merc A Class Merc C Class Motorbikes: XYZ: 500 600 So far I have this: $result = mysql_query("SELECT * FROM Cars")or die(mysql_error()); while ($row = mysql_fetch_array($result)) { // we get all of the items in this project and put them into a 3 part Array.... $assets= array('Name' => $row['Name], type_a' => $row['Type_A'], 'Type_B' => $row['Type_B']); } print_r($assets); Now this works fine, I end up with a 3 part array containing all of the information I need. The part I am struggling with, is how to get the information back out of the array in a way I can deal with, to produce the above example. Any help? Thanks guys!
  5. I have a set of tables for job listing. Right now I have a job table with id that is linked to multiple other tables that contain requirements for this job. For example: Job Responsiblities Job Duties Job Desired Skills Job Required Skills …..and so on. Lets say 10 different tables. The way my code is set up now I’m getting a couple levels of arrays returned. I’m wondering if there is a way to get rid of one of the levels. OR if this is how it should look. The returned data is displayed on a PHP Page. Some of the information returned is going to a table (Job Title, city, state, country). The rest - tables listed above will be put to a simple list in sections for each job. So an example of that will be: Job 1 Job Title Job Responsiblities list Job Duties list Job Desired Skills list Job Required Skills list Job 2 Job Title Job Responsiblities list Job Duties list Job Desired Skills list Job Required Skills list Here is what my return looks like using the <pre> </pre> tags Array ( [0] => Array ( [job_id] => 94 [jobOpening_ID] => 287 [customer] => customer [datePosted] => 2013-12-19 [dateRemoved] => 0000-00-00 [jobtitle] => jobTitle [city] => loc_city [state] => loc_State [country] => loc_Country [experience] => Experience [open] => 1 [summary] => Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary Summary [0] => Array ( [0] => Array ( [resp] => Array ( [0] => Job ID 94 Responsibility 1 [1] => Job ID 94 Responsibility 2 [2] => Job ID 94 Responsibility 3 [3] => Job ID 94 Responsibility 4 [4] => Job ID 94 Responsibility 5 ) ) ) [1] => Array ( [0] => Array ( [duties] => Array ( [0] => Job ID 94 Duty 1 [1] => Job ID 94 Duty 2 [2] => Job ID 94 Duty 3 [3] => Job ID 94 Duty 4 [4] => Job ID 94 Duty 5 ) ) ) ) [1] => Array ( [job_id] => 92 [jobOpening_ID] => 305 [customer] => Cust - ABC [datePosted] => 2013-12-12 [dateRemoved] => 0000-00-00 [jobtitle] => ABC Job Title [city] => Location City [state] => Location State [country] => Location Country [experience] => ABC Experience [open] => 1 [summary] => Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello [0] => Array ( [0] => Array ( [resp] => Array ( [0] => Job ID 92 Resp 1 [1] => Job ID 92 Resp 2 [2] => Job ID 92 Resp 3 [3] => Job ID 92 Resp 4 [4] => Upgrade hardware/software knowledge and skills through tutorials, seminars, and education ) ) ) [1] => Array ( [0] => Array ( [duties] => Array ( [0] => Job ID 92 Duty 1 [1] => Job ID 92 Duty 2 [2] => Job ID 92 Duty 3 [3] => Job ID 92 Duty 4 [4] => Job ID 92 Duty 5 ) ) ) ) ) I'm wondering if I can / should remove the third [0].. [0][0][0][resp] [0][0][0][duties] Code: function jb_return(){ try{ global $db; //Prepare query - Limit 2 now for testing $jb_return_set = $db->prepare("SELECT * from job order by job_id desc LIMIT 2"); //execute $jb_return_set->execute(); //Get results from returned object $jb_return_array = $jb_return_set->fetchAll(PDO::FETCH_ASSOC); //Transfer the returned array - Not sure if I need this, but I wanted to keep the original $jb_return_array as is $jb_full_array_return = $jb_return_array; /* * Get Job Specific Details */ $count = 0; foreach($jb_return_array as $cur_id){ //echo '<script type="text/javascript">alert("Job ID Returned is: '. $cur_id['job_id'] .'")</script>'; //Get Job Responsibilities and add the array to the job array $jb_resp= array(); $jb_resp = get_jb_resp($cur_id['job_id']); array_push($jb_full_array_return[$count], array($jb_resp)); //Get Job Duties and add the array to the job array $jb_duty= array(); $jb_duty = get_jb_duties($cur_id['job_id']); array_push($jb_full_array_return[$count], array($jb_duty)); //Get Job Skills and add the array to the job array //Get Job Desired Skills and add the array to the job array // and so on with the other tables ++$count; } //Return result return $jb_full_array_return; } catch(PDOException $e){ echo 'ERROR: Inside jb_return Function' . $e->getMessage(); } } function get_jb_resp($jb_id){ //echo '<script type="text/javascript">alert("Inside the get_jb_resp - Job ID is: '.$jb_id.'")</script>'; try{ global $db; //Prepare query $jb_resp_set = $db->prepare("SELECT resp from job_resp where job_id = :jb_id and resp !=\"\""); //Bind the Value $jb_resp_set->bindValue(':jb_id', $jb_id, PDO::PARAM_STR); //execute $jb_resp_set->execute(); //Get results from returned object $jb_resp_array = $jb_resp_set->fetchAll(PDO::FETCH_ASSOC); foreach ($jb_resp_array as $row){ $return_jb_resp_array['resp'][] = $row['resp']; } //return $jb_resp_array; return $return_jb_resp_array; } catch(PDOException $e){ echo 'ERROR: Inside get_jb_resp Function' . $e->getMessage(); } } function get_jb_duties($jb_id){ try{ global $db; //Prepare query $get_jb_duty_set = $db->prepare("SELECT duties from job_resp where job_id = :jb_id and duties !=\"\""); //Bind the Value $get_jb_duty_set->bindValue(':jb_id', $jb_id, PDO::PARAM_STR); //execute $get_jb_duty_set->execute(); //Get results from returned object $get_jb_duty_array = $get_jb_duty_set->fetchAll(PDO::FETCH_ASSOC); foreach ($get_jb_duty_array as $row){ $return_jb_duty_array['duties'][] = $row['duties']; } //return $jb_resp_array; return $return_jb_duty_array; } catch(PDOException $e){ echo 'ERROR: Inside get_jb_duties Function' . $e->getMessage(); } } As of now the total job responses are under 15, with multiple (random) items in the other tables.. thanx all
  6. I want to replace key words from an array in a user input string for all instances and case insensitive with the string "NOPE". An example array would be... var replacer = new Array("@", "$", "*", "drip", "slide", "move", "(", "\)"); Example: var userInput = "I have to slide down @ $3.00 with all (*) of the $ and moVe to another driping SLIDe"; *Magic replacement...* var output = "I have to NOPE down NOPE NOPE3.00 with all NOPENOPENOPE of the NOPE and NOPE to another NOPEing NOPE"; How would I do that?
  7. Sorry if my wording/terminalogy on the discription is wrong. I'm new to PHP, so i'll do my best to detail what im trying to do. The PHP is doing what i need it to do. But i do not need to print the whole response. I only need the [address] and [pubkey] values as variables. I have read a few tutorials, but they assume i already know the strings to be converted to variables. Please help Code... <?php require_once 'jsonClient.php'; $service = new jsonClient('http://ooples:booples@127.0.0.1:18332/'); $apple = array ($service->validateaddress("1234567890")); print_r ($apple); ?> Response... Array ( [0] => Array ( [isvalid] => 1 [address] => 1234567890 [ismine] => 1 [isscript] => [pubkey] => hqwiuehf9 [iscompressed] => 1 [account] => foo ) )
  8. Hi, I'm writing the following data to a text file. "name|price|image|text". The following code does exactly that. $filename = 'test.txt'; // Read file in to array. Each element is a line. $lines = file($filename, FILE_IGNORE_NEW_LINES); $data_to_add = $somecontent; // If the new data does not exist in the array if(!in_array($data_to_add, $lines)) { unset($lines[11]); // delete the 10th line array_unshift($lines, $data_to_add); // Put new data at the front of the array // Write the new array to the file file_put_contents($filename, implode("\n", $lines)); } I'm not sure what I ahve to do to make sure that the arrray only searches the first part of the data which in this case is "name" to make sure only unique data is saved?
  9. Hi guys, before I get to the main part of my question, I first wanted to ask whether there is a maximum number of values you should store in an array. If for example you have 5000 boxes that people can choose from and eventually all 5000 boxes will be chosen, is it save to store all of the chosen boxes in an array? For example box1,box5,box7,box21 are already chosen, then someone chooses box2,box3,box4 and it adds to the same array, is that feasible with up to 5000 values in total? My thoughts on it were that it would probably be more feasible than giving each box it's own column!? Secondly, assuming the above is ok, how would I go about ensuring nobody could choose a box already chosen? Basically, if somebody chooses box3 and box4, how can I check that these don't exist in the column before adding them so they don't duplicate? Hope this makes some sense and isn't just gobblydeegook! Finally, if somebody in the Users table chooses box3 and box4 from SaleID5, what would be the best way of storing what they've chosen in the User table to use the data when they're viewing what they've got?! Many thanks in advance guys.
  10. OK i am very new to PHP so please be gentle LOL. I am posting a form to Liveaddress API and then i get the response back in an array it looks like this Array ( [0] => Array ( [input_index] => 0 [candidate_index] => 0 [delivery_line_1] => 13700 Oakland St [last_line] => Highland Park MI 48203-3173 [delivery_point_barcode] => 482033173009 [components] => Array ( [primary_number] => 13700 [street_name] => Oakland [street_suffix] => St [city_name] => Highland Park [state_abbreviation] => MI [zipcode] => 48203 [plus4_code] => 3173 [delivery_point] => 00 [delivery_point_check_digit] => 9 ) [metadata] => Array ( [record_type] => S [zip_type] => Standard [county_fips] => 26163 [county_name] => Wayne [carrier_route] => C021 [congressional_district] => 14 [rdi] => Commercial [elot_sequence] => 0024 [elot_sort] => A [latitude] => 42.40858 [longitude] => -83.08783 [precision] => Zip9 ) [analysis] => Array ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y [footnotes] => L# ) ) ) How would i take primary_number and turn that into a variable to then insert into a database? Thanks, T
  11. I have the following code: <? Header("content-type: application/x-javascript"); $pathstring=pathinfo($_SERVER['PHP_SELF']); $locationstring="http://" . $_SERVER['HTTP_HOST'].$pathstring['dirname'] . "/"; function returnimages($dirname=".") { $pattern="(\.jpg$)|(\.jpeg$)|(\.gif$)"; $files = array(); $mostRecent=0; $curimage=0; if($handle = opendir($dirname)) { while(false !== ($file = readdir($handle))){ if(eregi($pattern, $file)){ echo 'picsarray[' . $mostRecent .']="' . $file . '";'; $mostRecent++; } } closedir($handle); } return($files); } echo 'var locationstring="' . $locationstring . '";'; echo 'var picsarray=new Array();'; returnimages() ?> I want to sort the images by reverse because This code sort pictures like this: picsarray[0]="2013-11-29 11:42:11 pm.jpg";picsarray[1]="2013-11-29 11:58:24 pm.jpg";picsarray[2]="2013-11-30 12:13:36 am.jpg";picsarray[3]="2013-11-30 12:27:46 am.jpg" I want to sort them by reverse. Anyone can help me to fix this problem?
  12. So this is my 2nd PHP class ever. And this right here is part of my final. I'm sure you all know what the "shuffle" function does. What I thought I could make it do was randomize a bunch of echoes I have. Is that possible? Any help would be greatly appreciated. KCCO! Here's the code I need tweaked: <html> <head> <title>Characters</title> <link rel="stylesheet" href="assets/css/bootstrap.css" media="screen"> <link rel="stylesheet" href="assets/css/bootstrap-responsive.css" media="screen"> <link rel="stylesheet" href="assets/css/normalize.css" type="text/css" media="screen"> <link rel="stylesheet" href="assets/css/style.css" media="screen"> </head> <body> <div class="navbar"> <div class="navbar-inner"> <a class="brand" href="#"></a> <ul class="nav"> <li class="active"><a href="Characters.php">Previous Clients</a></li> <li><a href="workForSupers.php">Work for Supers</a></li> </ul> </div> </div><!-- END of navbar--> <div align="center"> <h1>Supers we've helped locate</h1> <? date_default_timezone_set("America/Los_Angeles"); # set default timezone $imageDir = "images/"; # Comics is a PARENT class - Emily, Jenny, and so forth all are CHILDREN of Comics, meaning: They inherit the properties and methods included inside Comics. # For example: echo $joker->comiccharacters; will print out the $comiccharacters stored in Comics class Comics { const IMAGEDIR = "images/"; public $comiccharacters = "Comics"; } class Spiderman extends Comics { public $name = "Spiderman"; public $location = "New York City"; public $superpower = "his spider-sense, augmented speed and strength and his web shooters."; public $sex = "male"; public $published = "1963-03-01."; public $hero = true; public $asseskicked = 37; public $personscaught = [12,16,19,29,51]; public $powerlevel= '++++++'; public $email = "SpiderMan4Reals@gmail.com"; # A Constructor is automatically called when PHP is loaded public function __construct() { # set path for imageDir $this->imagePath = parent::IMAGEDIR . "spiderman.jpg"; } } $spiderman = new Spiderman(); class Magneto extends Comics { public $name = "Magneto"; public $location = "New York City."; public $superpower = "power of magnetism."; public $sex = "male"; public $published = "1963-10-15."; public $hero = false; public $asseskicked = 52; public $personscaught = [21,11,21,43,31]; public $powerlevel= '+++++++'; public $email = "ElMagneto@yahoo.com"; # A Constructor is automatically called when PHP is loaded public function __construct() { # set path for imageDir $this->imagePath = parent::IMAGEDIR . "magneto.jpg"; } } $magneto = new Magneto(); class Nightwing extends Comics { public $name = "Nightwing"; public $location = "Gotham City"; public $superpower = "is his peak physical conditioning, gadgets, and detective skills."; public $sex = "male"; public $published = "1985-01-06"; public $hero = true; public $asseskicked = 76; public $personscaught = [32,41,53,48,63]; public $powerlevel= '++++++'; public $email = "NightwingIsAwesome@hotmail.com"; # A Constructor is automatically called when PHP is loaded public function __construct() { # set path for imageDir $this->imagePath = parent::IMAGEDIR . "nightwing.jpg"; } } $nightwing = new Nightwing(); class GreenArrow extends Comics { public $name = "Green Arrow"; public $location = "Starling City"; public $superpower = "is his peak physical conditioning and accuracy with his gadgets."; public $sex = "male"; public $published = "1941-11-19"; public $hero = true; public $asseskicked = 62; public $personscaught = [17,17,29,31,49]; public $powerlevel= '++++++'; public $email = "ImTheGreenArrow@gmail.com"; # A Constructor is automatically called when PHP is loaded public function __construct() { # set path for imageDir $this->imagePath = parent::IMAGEDIR . "greenarrow.jpg"; } } $greenArrow = new GreenArrow(); class TheJoker extends Comics { public $name = "The Joker"; public $location = "Gotham City"; public $superpower = "being completely insane and psychotic."; public $sex = "male"; public $published = "1940-04-11"; public $hero = false; public $asseskicked = 112; public $personscaught = [61,79,103,94,52]; public $powerlevel= "++++++++"; public $email = "KillingForAJoke@gmail.com"; # A Constructor is automatically called when PHP is loaded public function __construct() { # set path for imageDir $this->imagePath = parent::IMAGEDIR . "joker.jpg"; } } $thejoker = new TheJoker(); # Create an array containing all the members classes $members = array($spiderman, $magneto, $nightwing, $greenArrow, $thejoker); # Calculate Ages - this cycles through all of the classes, and calculates the age for each band member, and places it in a property named "$age" foreach($members as $obj) { $obj->age = calculateAge($obj->published); } # Display our Jump Menu echo "<form name=\"jump\"> <p align=\"center\"> <select name=\"menu\" onchange='window.location.href=this.options[this.selectedIndex].value'> <option selected>All Characters</option> <option value=\"?sort=name\">Sort by Name</option> <option value=\"?sort=ageLoToHi\">Sort by Age (youngest to oldest)</option> <option value=\"?sort=ageHiToLo\">Sort by Age (oldest to youngest)</option> </select></p> </form>"; # Access the sort value from the url: blah.com/?sort=blam $sort = ''; if (isset($_GET['sort'])) { $sort = $_GET['sort']; } # Let's introduce all our members echo "<h2>Heroes and Villains Alike</h2>"; for ($i=0; $i < count($members); $i++) { switch ( $sort ) { # sort=name -- sorts alphabetically by 'name' in the member array case "name" : usort($members, 'sortByName_ascend'); displayProfile($members[$i]); break; case "nameRev" : usort($members, 'sortByName_descend'); displayProfile($members[$i]); break; # sort=ageLoToHi -- sorts alphabetically by 'age' ascending case "ageLoToHi" : usort($members, 'sortClassesByAgeLoHi'); displayProfile($members[$i]); break; # sort=ageHiToLo -- sorts alphabetically by 'age' descending case "ageHiToLo" : usort($members, 'sortClassesByAge_HiLo'); displayProfile($members[$i]); break; # sort=ageHiToLo -- sorts alphabetically by 'age' descending case "asseskicked" : uksort($members, 'sortAsseskicked'); displayProfile($members[$i]); break; # default -- spit out all band members according to their order in the array default : displayProfile($members[$i]); break; } } # This is a custom sorting function that works with usort(). # If you provide usort() with either an array or a set of objects, # it goes through all the items and compares them, and puts them in order # according to the rules below. function sortClassesByAgeLoHi($a, $b) { if ( $a->published == $b->published ) { #return 0; # this makes equivalent aged folks disappear return 1; } elseif ( $a->published > $b->published ) { return -1; } else { return 1; } } function sortClassesByAge_HiLo($a, $b) { return sortClassesByAgeLoHi($b, $a); # just reverse the arguments } function sortByName_ascend($a, $b) { if ( $a->name == $b->name ) { #return 0; # this makes equivalent aged folks disappear return 1; } elseif ( $a->name > $b->name ) { return 1; } else { return -1; } } function sortByName_descend($a, $b) { return sortByName_ascend($b, $a); # just reverse the arguments } # FUNCTIONS - Store all functions down here - I could also store them in another file function displayProfile($memberClass) { echo "<div class='memberProfile'><p>"; # spit out the image of our character # <img src="images/spiderman.jpg" /><br /> echo "<img src=\"".$memberClass->imagePath."\" width=200px /><br />"; #should make it so that when you refresh the page, it randomizes the order of the elements in the array shuffle($memberProfile); THE FOLLOWING IS SPECIFICALLY WHAT I WANT TO RANDOMIZE # spit out our caption echo "This is ".$memberClass->name.".<br>"; //counts the "+" for the power level echo "He has a power level of ".strlen($memberClass->powerlevel)." <br> "; echo "He resides in ".$memberClass->location.". <br>"; echo "He was first published in ".displayBirthdate($memberClass->published).".<br>"; echo "Making him ".calculateAge($memberClass->published)." years old! <br>"; //wraps the string after the specified # of characters echo "His superpower is ".wordwrap($memberClass->superpower,35,"<br>\n")."<br>"; echo "And in that time he's kicked the asses of ".$memberClass->asseskicked." people! <br>"; //finds the average & wraps the string after the specified # of characters echo "They normally capture their respective enemy ".average($memberClass->personscaught)." times a year.<br>"; echo "You can reach them at <a href=\"#\"> ".$memberClass->email.".</a>. <br> </p></div> "; } function displayBirthdate($bandmateBirthdate) { # January 1, 1984 $birthDateFormatted = date('F j, Y', strtotime($bandmateBirthdate)); return $birthDateFormatted; } function calculateAge($bandmateBirthdate) { #$currentTime = time(); # as a Unix timestamp list($year, $month, $day) = explode("-",$bandmateBirthdate); $elapsedYears = date('Y') - $year; $age = $elapsedYears; # calculates number of years elapsed # If current date < birthdate (i.e. Oct01 < Dec01), then subtract 1 year if ( date('n') < $month || ( date('n') == $month && date('j') < $day ) ) { $age = $age - 1; } return $age; } //example how to get the average in an array function average($average) { if (!is_array($average)) return false; return array_sum($average)/count($average); } ?> </body> <script type="text/javascript" src="js/bootstrap.js"></script> </html> Characters.php
  13. Dear Professional PHP Coders, I really need your help here. I am designing a form for registration (Please find the codes below). There are two errors I want corrected on this form. 1. PostBack data on controls. If a user submits a form, and there are errors on the submitted data, php should postback the user's submitted data on the controls. Instead of clearing them (i.e., setting the value to empty). 2. Display an array of all errors during form submission. Here, if a user has failed to provide necessary data on a selected controls, php should create an array of all controls wherein there are incorrect data, and php should echo the array of such incorrect errors below the form. (pls find the code below). I have tried something, but php is not echoing the assumed errors. No reporting at all. Please kindly help me. <?php //Connect to the database through our include include_once "/dat/connString_local.php"; //include the php file that checks whether a user is logged in or not include_once("toplinks_for_join_form.php"); //load the captcha code from the database $sql = mysql_query("SELECT id, captchacode, status FROM captcha"); while ($result = mysql_fetch_array($sql)) { $id = $result['id']; $captchacode_from_dbase = $result['captchacode']; } // echo $captchacode_from_dbase; // Set error message as blank upon arrival to page $errorMsg = array(); // First we check to see if the form has been submitted if (isset($_POST['username'])){ // Filter the posted variables // GET USER IP ADDRESS AND LOCATION DATA $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR')); $address1 = str_replace("[^A-Z a-z0-9]", "", $_POST['address1']); $address2 = str_replace("[^A-Z a-z0-9]", "", $_POST['address2']); $address = $address1 .", ". $address2 ." "; //CONCATENATE ADDRESS FIELDS INTO ONE VARIABLE $country = str_replace("[^A-Z a-z0-9]", "", $_POST['country']); // filter everything but spaces, numbers, and letters $state = str_replace("[^A-Z a-z0-9]", "", $_POST['state']); // filter everything but spaces, numbers, and letters $city = str_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters $address .=$city. ", " .$state. ", " .$country; //account info if($_POST['accounttype']=="atm"){ $accounttype = "ATM";}else {$accounttype = "eCurrency";} //$accounttype = str_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters $user_captcha = str_replace("[^0-9]", "", $_POST['captchacode']);//filter everything except numbers only //login data $username = str_replace("[^A-Za-z0-9]", "", $_POST['username']); // filter everything but numbers and letters $email = stripslashes($_POST['email']); $email = strip_tags($email); $email = mysql_real_escape_string($email); $password = str_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters $password2 = str_replace("[^A-Za-z0-9]", "", $_POST['password2']); // filter everything but numbers and letters //bio data $fullname = str_replace("[^A-Za-z]", "", $_POST['fullname']); // filter everything but upper and lowercase letters //find the gender if(($_POST['gender'])=="male"){ $gender = "m";} else {$gender = "f"; } //concatenate the date of birth fields $day = str_replace("[^0-9]", "", $_POST['day']);//filter everything except numbers only $month = str_replace("[^0-9]", "", $_POST['month']);//filter everything except numbers only $year = str_replace("[^0-9]", "", $_POST['year']);//filter everything except numbers only $dob = $year."/".$month."/".$day; //mysql accepts date string starting from year, month then day. $bio = str_replace("[^A-Z a-z0-9]", "", $_POST['bio']); // Check to see if the user filled all fields with // the "Required"(*) symbol next to them in the join form // and print out to them what they have forgotten to put in if(isset($_POST['btn_register'])){ if(!$fullname){$errorMsg[] .= "---Full Name must be characters only and not spaces.<br />";}//die($errorMsg.); else if(!isset($_POST['gender'])){$errorMsg = "---Please select gender.<br />";}//die($errorMsg.= else if(!$day){$errorMsg[] .= "---You must enter your valid date of birth.<br />";}//die($errorMsg. else if(!$month){$errorMsg[] .= "---You must enter your valid date of birth.<br />";}//die($errorMsg.= else if(!$year){$errorMsg[] .= "---You must enter your valid date of birth.<br />";}//die($errorMsg.= else if(!$bio){$errorMsg[] .= "---Please tell us about yourself.";}//die($errorMsg.= else if(strlen($bio) < 100){$errorMsg[] = "---Please tell us about yourself. Minimum of 100 xters.<br />";}//die( else if(!$address1){$errorMsg[] .= "---Address is compulsory please.<br />";}//die($errorMsg.= else if(!$city){$errorMsg[] .= "---Please enter your city location.<br />";}//die($errorMsg.= else if(!$state){$errorMsg[] .= "---Please enter or select a state where you come from.<br />";}//die($errorMsg.= else if(!$country){$errorMsg[] .= "---Please select your country from the list.<br />";}//die($errorMsg.= else if(!$email){$errorMsg[] .= "---You must enter a valid email address.<br />";}//die($errorMsg.= else if(!$username){$errorMsg[] .= "---Your username is required please.<br />";}//die($errorMsg.= else if(!$password){$errorMsg[] .= "---Password is required.<br />";}//die($errorMsg.= else if(strlen($password) < {$errorMsg[] = "---Invalid password. Min of 8 characters are required, max is 20.<br />";}//die( else if(!$password2){$errorMsg[] .= "---Please repeat password.<br />";}//die($errorMsg.= else if($user_captcha!=$captchacode_from_dbase){$errorMsg[] .= "---Please enter the correct CAPTCHA code.<br />";}//die($errorMsg.= else if(!$accounttype){$errorMsg[] .= "---Please select account type or mode of transaction.<br />";}//die($errorMsg.= else if(!$ip){$errorMsg[] .= "---Your location cannot be determined. You will not be allowed to continue the registration.<br />";}//die( elseif($country=="Select your country"){$errorMsg[] .= "Invalid Country selection.<br />";} else if($accounttype=="Select account type"){$errorMsg[] .= "Invalid Account Type selection.<br />";} //die($errorMsg); else if($password!=$password2){$errorMsg[] .= "---Passwords did not match. Repeat correct passwords please.<br />";}//die( else if($month > 12){$errorMsg[] .= "---Invalid month in date of birth.<br />";}//die( else if($day > 31 || $day =="00"){$errorMsg[] .= "---Invalid day of birth.<br />";}//die( else if($year < 1960 || $year > 1995 ){$errorMsg[] .= "---You are not qualified for this registration.<br />";}//die( else { //update the captcha table with a new generated captcha code // this file regenerates the captcha code if it is less than 50. require("update_captcha.php"); // Database duplicate Fields Check $sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1"); $sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1"); $username_check = mysql_num_rows($sql_username_check); $email_check = mysql_num_rows($sql_email_check); if($username_check > 0){ $errorMsg = "<u>ERROR:</u><br />Sorry, our system does not accept the username that you are using. Please try another."; die($errorMsg); } else if($email_check > 0){ $errorMsg = "<u>ERROR:</u><br />Sorry, our system does not accept the email that you are using. Please try another."; die($errorMsg);} } }//close the blocked if(isset)else { // Add MD5 Hash to the password variable $hashedPass = md5($password); // Add user info into the database table, claim your fields then values $sql = mysql_query("INSERT INTO members (fullname,gender,dob,bio,ip,username,address,country,state,city,accounttype,email, password, signup_date) VALUES('$fullname', '$gender','$dob','$bio','$ip','$username','$address','$country','$state','$city','$accounttype','$email','$hashedPass', now()) ") or die (mysql_error()); // Get the inserted ID here to use in the activation email $id = mysql_insert_id(); // Create a directory(folder) to hold each user files(pics, MP3s, etc.) mkdir("memberFiles/$id", 0755); //echo "Yes, " .$_POST['btn_register']. "<br />Username: ".$_POST['username']. "<br />Gender: ". $gender. "<br />Captcha: ". $user_captcha. //"<br />Account Type: ".$accounttype. "<br />Address: ".$address; //send the maill first before adding to the database //compose email function here $to = "$email"; $subject = "Complete your registration - Authentication Needed!"; //Begin HTML Email Message where you need to change the activation URL inside $message = '<html> <body bgcolor="#FFFFFF"> Hi ' . $fullname . ', <br /><br /> You have successfully created an account with us.<br /><br /> Your Login information is as follows: <br /><br /> Your E-mail Address: ' . $email . ' <br /> Your Password: ' . $password . ' <br /><br /> Your Account / Payment / Transaction information: '.$accounttype. '. <br /><br /> In order to be able to use your account, you must complete this step to activate your account by clicking on the Account Activation Link below. <br /><br /> Please click the link to activate now >> <a href="http://localhost/easytimecorporation.com/lotto/activation.php?id=' . $id . '"> ACTIVATE NOW</a><br /> Thanks! <br /><br /> Eyo Honesty, <br /> Easytime Corporation. </body> </html>'; // end of message //import the email settings file here. include_once('emailSettings.php'); //check whether the mail is sent or not if($mail->Send()) { //echo "Message has been sent"; // Then print a message to the browser for the joiner $message2 = '<br /> Hi ' . $fullname . ', <br /><br /> You have successfully created an account with us. A mail has been sent to you at ' .$email. '.<br /><br /> In order to be able to use your account, please check your email and click on the Account Activation Link to activate your account. <br /><br /> Thank you'; //echo $message2; //update the captcha table with a new generated captcha code // this file regenerates the captcha code if it is less than 50. require("update_captcha.php"); //redirect user to success.php $_SESSION['msg'] = $message2; //echo $_SESSION['msg']; //header("location: register_success.php?id=".$_SESSION['msg']); } else { //delete the user from database and delete the created user directory require("delete_user.php"); rmdir("memberFiles/$id");//removes a created directory. //update the captcha table with a new generated captcha code // this file regenerates the captcha code if it is less than 50. require("update_captcha.php"); die("Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo); exit(); } // Exit so the form and page does not display, just this success message }//close the $_POST[''] check line ?> <!DOCTYPE html> <HTML> <HEAD> <META CHARSET="UTF-8"> <LINK rel="icon" href="images/blueweb.ico" type="image/x-icon"> <LINK rel="stylesheet" href="style/style.css"> <TITLE>Users Registration Form.</TITLE> <STYLE type="text/css"> <!-- .style1 {color: #FF0000} .style3 {color: #FF0000; font-weight: bold; } --> </STYLE> </HEAD> <BODY> <?php include_once("template_pageTop.php");?> <DIV id="pageMiddle"> <FORM name="joinForm" id="joinForm" action="join_form.php" method="post" enctype="multipart/form-data"> <DIV align="center"> <H1>Users Registration Form</H1> <HR style="width:80%; outline-style:groove; outline-color:#CCCCCC;"> <DIV align="justify"> <LEGEND style="margin-left:20px; "><STRONG><u>Basic Data</u></STRONG> Please all starred <SPAN class="style1">*</SPAN> fields in red colour are required.</LEGEND> <BR /> <TABLE width="800" border="0" align="center" cellpadding="2" cellspacing="5" style="border-radius:10px; background-color:#006699; color:#FFFFFF;"> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Full Name:</STRONG></TD> <TD width="520" align="left" valign="middle"><INPUT type="text" name="fullname" value="<?php if (isset($_POST['fullname'])) {echo "$fullname";} ?>" size="80" maxlength="40"></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Gender:</STRONG></TD> <TD width="520" align="left" valign="middle"> <LABEL> <INPUT type="radio" name="gender" value="male"> Male</LABEL> <INPUT type="radio" name="gender" value="female"> Female</LABEL></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Date of Birth:</STRONG></TD> <TD width="520" align="left" valign="middle"> Day <INPUT type="text" name="day" value="<?php if (isset($_POST['day'])) {echo "$day";} ?>" size="5" maxlength="2"> Month <INPUT type="text" name="month" value="<?php if (isset($_POST['month'])) {echo "$month";} ?>" size="5" maxlength="2"> Year <INPUT type="text" name="year" value="<?php if (isset($_POST['year'])) {echo "$year";} ?>" size="10" maxlength="4"> format --> DD / MM / YYYY </TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><STRONG><SPAN class="style1">*</SPAN> Tell us about yourself: </STRONG><EM>(min = 100 characters).</EM> </TD> <TD width="520" align="left" valign="middle"><TEXTAREA name="bio" cols="50" rows="4"><?php if (isset($_POST['bio'])) {echo "$bio";} ?></TEXTAREA></TD> </TR> </TABLE> </DIV> <HR style="width:80%; outline-style:groove; outline-color:#CCCCCC;"> <DIV align="justify"> <LEGEND style="margin-left:20px; "><STRONG><u>Location Data</u></STRONG> Please all starred <SPAN class="style1">*</SPAN> fields in red colour are required.<BR> </STRONG></u></LEGEND><BR /> <TABLE width="800" border="0" align="center" cellpadding="2" cellspacing="5" style="border-radius:10px; background-color:#006699; color:#FFFFFF;"> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Address 1 :</STRONG></TD> <TD><INPUT name="address1" type="text" size="80" maxlength="70" value="<?php if (isset($_POST['address1'])) {echo "$address1";} ?>" /></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><STRONG>Address 2 (<EM>optional</EM>) :</STRONG></TD> <TD><INPUT name="address2" type="text" size="80" maxlength="70" value="<?php if (isset($_POST['address2'])) {echo "$address2";} ?>" /></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> City:</STRONG></TD> <TD><INPUT name="city" type="text" size="50" maxlength="30" value="<?php if (isset($_POST['city'])) {echo "$city";} ?>" /></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> State:</STRONG></TD> <TD><INPUT name="state" type="text" size="50" maxlength="25" value="<?php if (isset($_POST['state'])) {echo "$state";} ?>" /></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Country :</STRONG></TD> <TD><SELECT name="country"> <OPTION value="Select your country" selected="selected">Select your country</OPTION> <OPTION value="Australia">Australia</OPTION> <OPTION value="Canada">Canada</OPTION> <OPTION value="Mexico">Mexico</OPTION> <OPTION value="United Kingdom">United Kingdom</OPTION> <OPTION value="United States">United States</OPTION> <OPTION value="Zimbabwe">Zimbabwe</OPTION> <OPTION value="Cameroon">Cameroon</OPTION> <OPTION value="Nigeria">Nigeria</OPTION> <OPTION value="South Africa">South Africa</OPTION> <OPTION value="Uganda">Uganda</OPTION> <OPTION value="Thailand">Thailand</OPTION> <OPTION value="Brazil">Brazil</OPTION> <OPTION value="China">China</OPTION> <OPTION value="Japan">Japan</OPTION> <OPTION value="Korea">Korea</OPTION> <OPTION value="DR Congo">DR Congo</OPTION> <OPTION value="Egypt">Egypt</OPTION> <OPTION value="Germany">Germany</OPTION> <OPTION value="Bene Republic">Bene Republic</OPTION> <OPTION value="Niger">Niger</OPTION> <OPTION value="Saudi Arabia">Saudi Arabia</OPTION> <OPTION value="Italy">Italy</OPTION> <OPTION value="France">France</OPTION> <OPTION value="India">India</OPTION> <OPTION value="Malaysia">Malaysia</OPTION> <OPTION value="Spain">Spain</OPTION> <OPTION value="Portugal">Portugal</OPTION> <OPTION value="Port De Spain">Port De Spain</OPTION> <OPTION value="Trinidad and Tobago">Trinidad and Tobago</OPTION> <OPTION value="Chile">Chile</OPTION> </SELECT></TD> </TR> </TABLE> </DIV> <HR style="width:80%; outline-style:groove; outline-color:#CCCCCC;"> <DIV align="justify"> <LEGEND style="margin-left:20px; "><U><STRONG>Login Information</STRONG></U> Please all starred <SPAN class="style1">*</SPAN> fields in red colour are required.</LEGEND> <BR /> <TABLE width="800" border="0" align="center" cellpadding="2" cellspacing="5" style="border-radius:10px; background-color:#006699; color:#FFFFFF;"> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Username:</STRONG></TD> <TD><DIV align="left"> <INPUT name="username" type="text" size="50" maxlength="25" value="<?php if (isset($_POST['username'])) { echo "$username";} ?>" /> </DIV></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><P><SPAN class="style3">*</SPAN><STRONG> Password: </STRONG></P> <P><EM>(8 characters minimum, 20 max.) </EM></P></TD> <TD><DIV align="left"> <INPUT name="password" type="password" value="<?php if (isset($_POST['password'])) {echo "$password";} ?>" size="40" maxlength="20"> No spaces or special charactes. </DIV></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><P><SPAN class="style3">*</SPAN><STRONG> Repeat Password</STRONG></P> <P><EM>(8 characters minimum, 20 max.) </EM></P></TD> <TD><DIV align="left"> <INPUT name="password2" type="password" value="<?php if (isset($_POST['password2'])) {echo "$password2";} ?>" size="40" maxlength="25"> No spaces or special charactes. </DIV></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> E-mail Address</STRONG></TD> <TD><DIV align="left"> <INPUT name="email" type="text" value="<?php if (isset($_POST['email'])) {echo "$email";} ?>" size="80" maxlength="45" /> </DIV></TD> </TR> </TABLE> </DIV> <HR style="width:80%; outline-style:groove; outline-color:#CCCCCC;"> <DIV align="justify"> <LEGEND style="margin-left:20px; "><U><STRONG>Account / Payment Information</STRONG></U> Please all starred <SPAN class="style1">*</SPAN> fields in red colour are required.</LEGEND> <BR /> <TABLE width="800" border="0" align="center" cellpadding="2" cellspacing="5" style="border-radius:10px; background-color:#006699; color:#FFFFFF;"> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> Account Type:</STRONG></TD> <TD><SELECT name="accounttype" size="3"> <OPTION value="Select account type">Select Account Type</OPTION> <OPTION value="atm">ATM</OPTION> <OPTION value="ecurrency" selected>e-Currency</OPTION> </SELECT></TD> </TR> <TR> <TD align="right" valign="middle" style="width:260px; height:40px; padding:15px;"><SPAN class="style3">*</SPAN><STRONG> CAPTCHA:</STRONG></TD> <TD> <INPUT name="captchacode" type="text" value="<?php if (isset($_POST['captchacode'])) {echo "$user_captcha";}?>" maxlength="12"> <?php echo "<font style ='color:#ffff00; font-size:20px; font-weight:bolder; font:Broadway;'> $captchacode_from_dbase</FONT> <font style='color:#ffffff;'-->Enter the code shown.</FONT>";?> </TD> </TR> </TABLE> </DIV> <HR style="width:80%; outline-style:groove; outline-color:#CCCCCC;"> <DIV align="left" style="margin-left:0px;"> <DIV align="center"> <INPUT name="btn_register" type="submit" value="R E G I S T E R"> <INPUT name="reset" type="reset" value="R E S E T" style="font:Georgia, 'Times New Roman', Times, serif; font-size:14px;"> <BR /><BR /> </DIV> </DIV> <?php if (empty($errorMsg)=== false) { echo '<ul>'; foreach($errorMsg as $error) { echo '<li>', $error, '</li>'; } echo '</ul>'; } ?> </FORM> </DIV> <?php include_once("template_pageBottom.php");?> </BODY> </HTML> join_form.php
  14. Hey guys, I am working for the first time without a database and MySQL while using PHP. anyway i am working on a real estate page and i am having issues on the "areas we cover", and this section would allow a user to view the neighborhoods or locations that the real estate agent has listings or does showings. i created a multidimensional array with the data i need. <?php $cities = array('pasadena' => array( "name" => "Pasadena", "picture" => "pasadena.png", "link" => "https://maps.google.com/maps?q=pasadena+ca&ie=UTF-8&ei=21uRUqGUKY3VoATvsILwDA&ved=0CAgQ_AUoAg", "value" => "1", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Pasadena/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Pasadena/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'glendale' => array( "name" => "Glendale", "picture" => "glendale.png", "link" => "https://maps.google.com/maps?q=glendale+ca&ie=UTF-8&ei=wFuRUvSBFNLroASkvYKgDw&ved=0CAgQ_AUoAg", "value" => "2", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Glendale/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Glendale/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'eagle rock' => array( "name" => "Eagle Rock", "picture" => "eagle.png", "link" => "https://maps.google.com/maps?q=eagle+rock+maps&ie=UTF-8&ei=cluRUtLDB9LuoASw8YDoDw&ved=0CAgQ_AUoAg", "value" => "3", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Eagle_Rock/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Eagle_Rock/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'silverlake' => array( "name" => "Silverlake", "picture" => "silverlake.png", "link" => "https://maps.google.com/maps?q=Silverlake+Ca&ie=UTF-8&ei=VFuRUrOLJMXwoASt74CQDQ&ved=0CAoQ_AUoAg", "value" => "4", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Silver_Lake/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:absolute;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/90026"></script></div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'atwater' => array( "name" => "Atwater Village", "picture" => "atwater_village.png", "link" => "https://maps.google.com/maps?q=atwater+village&ie=UTF-8&hq=&hnear=0x80c2c0e875cbce3b:0x99ebb9fd977ae16f,Atwater+Village,+Los+Angeles,+CA&gl=us&ei=kVGRUrzgHoTloAT_u4HADg&ved=0CKYBELYD", "value" => "5", "details" => "This is where the details will go", 'data' => '', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:absolute;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/90026"></script></div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'palmdale' => array( "name" => "Palmdale", "picture" => "palmdale.png", "link" => "https://maps.google.com/maps?q=Palmdale+Ca&ie=UTF-8&ei=G1qRUti1NonuoASHsIK4Cw&ved=0CAoQ_AUoAg", "value" => "6", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Palmdale/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Palmdale/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'lancaster' => array( "name" => "Lancaster", "picture" => "lancaster.png", "link" => "https://maps.google.com/maps?q=Lancaster+CA&ie=UTF-8&ei=elqRUqT_D8HroASK-oGwDw&ved=0CAgQ_AUoAg", "value" => "7", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Lancaster/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Lancaster/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'burbank' => array( "name" => "Burbank", "picture" => "burbank.png", "link" => "https://maps.google.com/maps?q=Burbank+Ca&ie=UTF-8&ei=qlmRUuKXF5HroATysoJI&ved=0CAoQ_AUoAg", "value" => "8", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Burbank/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Burbank/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'altadena' => array( "name" => "Altadena", "picture" => "altadena.png", "link" => "https://maps.google.com/maps?q=altadena+ca&ie=UTF-8&ei=01iRUrW1I8zloATwn4KgBA&ved=0CAoQ_AUoAg", "value" => "9", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Altadena/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Altadena/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), 'z_all' => array( "name" => "Sorry! Didn't find your city? We can show more.", "picture" => "all.png", "link" => "contact_us.php", "value" => "10", "details" => "This is where the details will go", 'data' => '<div id="tGraphs" style="border: 1px solid #ccc; padding: 5px 0px 5px 0px; width:300px; text-align:center;"><script language="javascript" type="text/javascript" src="http://synd.trulia.com/tools/chart/style_default300/type_average_listing_price/CA/Altadena/"></script></div>', 'second_image' => '<img src="altadena_home.jpg" height="195" width="200">', 'trulia' => '<style type="text/css"> .module {overflow:visible;}/*For typepad*/ #tMinistats { position:relative; width:180px; } #tMinistats .tMinistatsS { text-align:center; position:relative;bottom:0;margin-bottom:70px;width:95%; z-index:100;color:#b6d46f;font-family:Arial;font-size:11px; } #tMinistats .tMinistatsS a { color:#06c; }</style><div id="tMinistats" style="background-color:#ffffff;"> <script type="text/javascript" language="javascript" src="http://synd.trulia.com/tools/ministats/style_default180/CA/Altadena/"></script> </div>', 'second_image' => '<div style="position:relative; top:-30px; left:10px; border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena1.jpg" alt="Altadena Home" height="250" width="220"></div>', 'third_image' => '<div style="position:relative; top:-282px; left:260px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena2.jpg" alt="Altadena Home" height="250" width="220"></div>', 'fourth_image' => '<div style="position:relative; top:-535px; left:510px;margin-bottom: -500px;border: 2px solid black; height: 250px; width: 220px;"><img src="images/cities/altadena/altadena3.jpg" alt="Altadena Home" height="250" width="220"></div>' ), ); sort($cities); ?> I originally created this page as a single page layout that would have all the areas listed then would have them looking like a nice organized list. i called this page area_showings.php i created a foreach() loop that would call the array then the value foreach($cities as $city => $data){} this worked perfectly and was calling the data to the variable value and i could set the page up. I then decided that the idea of a long list of cities was not very user friendly and i decided to make is a dynamic page with a different structure. i wanted the user to go on area_showings.php and there he would select a link of his city interested in, and the page would then load the data based upon what the user had selected. <?php foreach ($cities as $city => $data){ echo <a href="area_showings.php?city=' . $data['name'] .'">'. $data['name'] . '</br></div>'; } ?> Now when a user selects the city he should be directed to the same page but now it would show the direct data based on the URL. This works fine and is passed correctly with the $_GET. MY ISSUE: I have created my conditional to check if the $_GET is empty or matches the correct city. but after the conditional i cant seem to understand how i can call the same $data[]; without a loop. i am use to MySQL where you can call for the $data using fetch_assoc to create the variables. if (empty($_GET['city']) === true){ ?> <div style="background-color:#A9B9C9;width:780px; height: auto; padding-left: 30px;padding-top: 30px; margin-left: 200px; margin-bottom: 20px; margin-top: 10px; border: black 5px solid;line-height: 25px;"> <?php foreach ($cities as $city => $data){ echo '<div style="height: 50px; width: auto; border: black solid 2px;font-size: 1.2em; padding: 10px 10px;"> <a href="area_showings.php?city=' . $data['name'] .'">'. $data['name'] . '</br></div>'; } ?> </div> <?php } else if (empty($_GET['city']) === false) { $name = $_GET['city']; if($name == 'Burbank' || $name == 'Glendale' || $name == 'Atwater Village' || $name == 'Pasadena' || $name == 'Altadena' || $name == 'Eagle Rock' || $name == 'Silverlake' || $name == 'Lancaster' || $name == 'Palmdale' || $name == 'Echo Park' || $name == 'Sorry! Didn\'t find your city? We can show more.'){ echo '<div style="background-color: #fff;padding: 10px 10px;height: auto; width:750px;border: 2px solid #000; border-radius: 15px;"> echo '<div style="background-color: #fff;padding: 10px 10px;height: auto; width:750px;border: 2px solid #000; border-radius: 15px;"> <div style="font-family:Lato, sans-serif, Helvetica, sans-serif;color:#2B4450; font-size: 30px; font=weight:bolder;margin-bottom:15px;margin-top:15px; text-transform: uppercase;">' . $data['name'] . '</div> <div style="height:250px; width:200px; border: black 4px solid; margin-bottom: -200px;"><a href="' . $data['link'] .'" target="_blank"><img src="images/cities/' . $data['picture'] . '" height="250" width="200"></a></div> <div style="position:relative;top:-55px;left:220px;height:250px; width: 0px;line-height:-50px;margin-top:-120px; padding-left: 10px; padding-top: 10px;border-radius: 10px;">' .$data['data'] . '<span style="position:relative; top: -200px; left: 320px;">' .$data['trulia'] . '</span></div><div style="width:auto; height; 300px; border-bottom: 3px solid black;">' . $data['second_image'] . $data['third_image'] . $data['fourth_image'] . '</div> <h2><span style="color:#2B4450; font-weight: bolder; font-family:Lato, sans-serif, Helvetica, sans-serif;">For more info</span> <a href="contact_us.php" class="info_Button">Click Here</a></h2> </div> </br>'; </div> </br>'; } } so just to clarify, i want to be able to use the correct array of data to the matching city of the $_GET with a multidimensional array without using a foreach loop. i want the info to be dynamic not listed. any suggestions ? implode function ? array_walk ?
  15. When using the following code: $yaxis=array(); $xaxis=array(); for ($i = 1; $i <= $number_of_entries; $i++) { $channel = $xml->xpath("//ns:BulkData[ns:Name='InternetGatewayDevice.LANDevice.1.WLANConfiguration.X_181BEB_ChannelDiagnostics.Result.{$i}.Channel']/ns:Value"); $channel = $channel[0]; $xaxis[]=$channel[0]; $apcount = $xml->xpath("//ns:BulkData[ns:Name='InternetGatewayDevice.LANDevice.1.WLANConfiguration.X_181BEB_ChannelDiagnostics.Result.{$i}.APcount']/ns:Value"); $apcount = $apcount[0]; $yaxis[]=$apcount[0]; } I get the following results for $xaxis and $yaxis arrays: print_r($xaxis); Array ( [0] => SimpleXMLElement Object ( [0] => 1 ) [1] => SimpleXMLElement Object ( [0] => 6 ) [2] => SimpleXMLElement Object ( [0] => 11 ) ) print_r($yaxis); Array ( [0] => SimpleXMLElement Object ( [0] => 3 ) [1] => SimpleXMLElement Object ( [0] => 8 ) [2] => SimpleXMLElement Object ( [0] => 6 ) ) What I am looking for is only the value of the nested array. Like this: print_r($xaxis); Array ( [0] => 1 [1] => 6 [2] => 11 ) print_r($yaxis); Array ( [0] => 3 [1] => 8 [2] => 6 ) How can I achieve this? Thanks for any help / suggestions!
  16. Hello all. I have tried to figure out why I can't make a certain part of my code sticky. I am attempting to save the user's input for the radio button section. I am using a foreach loop for everything in my array. When I try to use if isset, it returns the last item in the array instead of what was selected by the user. Here is the code: <?php //Creating foreach loop for magazine selection foreach ($magSubs as $mag => $SUB_PRICE) { echo "<input type='radio' name='magtype' value='$mag' />$mag $$SUB_PRICE per month<br> "; } ?> Again, I want to make this part sticky.
  17. I have this array and I need to search it for the 'id' for a specific value $id. What i'm trying to do is get the position in the array of the id i'm searching for. I have tried $position = array_search($id, $rows); but I get bool false The contents of $rows (taken from MySQL database) is array( { [0]=> array(1) { ["id"]=> string(2) "24" } [1]=> array(1) { ["id"]=> string(2) "22" } [2]=> array(1) { ["id"]=> string(2) "12" } [3]=> array(1) { ["id"]=> string(2) "11" } [4]=> array(1) { ["id"]=> string(1) "8" } [5]=> array(1) { ["id"]=> string(1) "6" } [6]=> array(1) { ["id"]=> string(1) "5" } [7]=> array(1) { ["id"]=> string(1) "4" } }
  18. I've got this sample of array data Array ( [0] => stdClass Object ( [fileid] => 333 [filename] => Douglas [datecreated] => 2013-10-25 09:53:27 [datemodified] => 2013-10-25 09:53:27 [fileAccess] => 1 [user_id] => 70 ) [1] => stdClass Object ( [fileid] => 326 [filename] => Yeah baby [datecreated] => 2013-10-24 09:02:05 [datemodified] => 2013-10-24 09:02:05 [fileAccess] => 1 [user_id] => 70 ) [2] => stdClass Object ( [fileid] => 329 [filename] => UNTITLED File [datecreated] => 2013-10-25 07:14:53 [datemodified] => 2013-10-25 07:14:53 [fileAccess] => 1 [user_id] => 70 ) [3] => stdClass Object ( [fileid] => 330 [filename] => UNTITLED FILE [datecreated] => 2013-10-25 07:17:55 [datemodified] => 2013-10-25 07:17:55 [fileAccess] => 1 [user_id] => 70 ) [4] => stdClass Object ( [fileid] => 332 [filename] => UNTITLED FILE [datecreated] => 2013-10-25 08:42:35 [datemodified] => 2013-10-25 08:42:35 [fileAccess] => 1 [user_id] => 70 [statuss] => 1 ) ) and by fileid I would like to check if the fileid is also existing on the other mysql. . so I did this foreach($array as $key => $row){ $query = $this->model->get($row->fileid); //query return true or false; if($query){ $array[$key]['stared'] = 1; } } but it gives an error. How will I going to insert a new variable on the current array loop if the fileid is existing. e.g. [4] => stdClass Object ( [fileid] => 332 [filename] => UNTITLED FILE [datecreated] => 2013-10-25 08:42:35 [datemodified] => 2013-10-25 08:42:35 [fileAccess] => 1 [user_id] => 70 [statuss] => 1 [stared] => 1 //IF STARED RETURN TRUE ) Thanks
  19. I have a function that updates a database and it works fine for one record but i have a form which shows loads of rows with checkboxes and i want to do a batch update (I suppose the principle is the same for a batch delete). When I click a load of checkboxed and call the funtion to update, i get an error about an array to string conversion and also this error message "Unknown column 'Array' in 'where clause" I know a way around it but it's not great using a foreach loop to update the database but that involves loads of queries This is my function I call to update the database /** * update * @param string $table A name of table to insert into * @param string $data An associative array * @param string $where the WHERE query part */ public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach($data as $key=> $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key => $value) { $sth->bindValue(":$key", $value); } $sth->execute(); } This works public function newsEdit($data) { $postData = array( 'title' => $data['news_title'], 'content' => $data['news_content'], 'photo' => $data['imgname'], 'keywords' => $data['news_keywords'], 'alternate' => $data['alternate'] ); $this->db->update('news', $postData, "`id` = {$data['newsid']}"); } $data = array(); $data['news_title'] = $_POST['news_title']; $data['news_content'] = $_POST['news_content']; $data['imgname'] = $_POST['imgname']; $data['news_keywords'] = $_POST['news_keywords']; $data['alternate'] = substr($_POST['imgname'],0,strrpos($_POST['imgname'], ".")); newsEdit($data); This doesn't public function newsArchive($ids) { $postData = array( 'archived' => 'Y' ); $this->db->update('news', $postData, "`id` IN ({$ids})"); } newsArchive($_POST['id']); What have i got to change to get the update working?
  20. Hi, I have the following array and would like to loop through it and check if there are duplicate catalogIDs, if yes, I would like to compare the dates and choose the earliest date. In the following array: catalogID 1257 is there two times. I need earliest date, which is 2013-09-03 catalogID 1340 is there three times. I need earliest date, which is 2013-09-04 Array ( [0] => 1159, 2013-09-03 [1] => 1157, 2013-09-03 [2] => 1257, 2013-09-03 [3] => 1257, 2013-09-13 [4] => 1340, 2013-09-04 [5] => 1335, 2013-09-03 [6] => 1340, 2013-09-13 [7] => 1410, 2013-09-03 [8] => 1340, 2013-09-18 ) Is it easier to add all the unique catalogIDs with the earliest date to a new array or remove the duplicate catalogIDs with the late dates from the current array? I have tried a foreach loop and a for loop with counter but I'm not able to do this. Any ideas? Thanks!
  21. I have my program working but it needs an very bad improvement. How it works, my program turns each line in a .txt file it grabs into an array every time it executes code it loops back to open the .txt file again and turns it into an array now grabbing the second line and so forth. It's a 4 MB file but I came to the conclusion that the reason I'm having such a high server transfer rate up to GB's is because the server has to use a lot more to turn into a new array every time the file() command is used. I came up with an idea after 3 days of thinking that I should use the program to open up the file only once turning it into an area and just use all the arrays without reopening the file and creating a new one. I was thinking of doing this but not sure it will work. <?php $fetch_data = file('http://somesite.com/text.txt'); $x=1; $i=0 while($x<=80) { $data = $fetch_data[$i]; Execute some code $i++ $x++ } ?> Would this work looping each line in the file without creating a new array each time?
  22. How do you selectively BOLD output array elements from three arrays? My code has only one output line. I am creating a madlib php program and I want my nouns to be in bold, my verbs to be italicized, and my adjectives to be underlined. Where would I implement this? Thanks. Here is my code: $counter=0; $nounCounter=0; $verbCounter=0; $adjCounter=0; $newSentArray = $sentArray; // copy $sentArray while ( $counter < count($sentArray)) // loop over words in array { if($sentArray[$counter] == "NOUN" or $sentArray[$counter] == "NOUN." or $sentArray[$counter] == "NOUN!") { // replace current word with noun $newSentArray[$counter] = $nounArray[$nounCounter]; $nounCounter++; // increment noun, so next noun in used for replacement } elseif($sentArray[$counter] == "VERB" or $sentArray[$counter] == "VERB." or $sentArray[$counter] == "VERB!") { // replace current word with verb $newSentArray[$counter] = $verbArray[$verbCounter]; $verbCounter++; // increment verb, so next verb in used for replacement } elseif($sentArray[$counter] == "ADJECTIVE" or $sentArray[$counter] == "ADJECTIVE." or $sentArray[$counter] == "ADJECTIVE!") { // replace current word with adjective $newSentArray[$counter] = $adjArray[$adjCounter]; $adjCounter++; // increment adjective, so next adjective in used for replacement } $counter++; } // implode words array into a string echo implode(' ', $newSentArray);
  23. I have this function that creates breadcrumbs from the URL It appears to work but i get these error messages Line 13 points to $base_url = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; and line 16 is $last = end(array_keys($path)); Any ideas how i can remove these errors/warnings? here is the code public function breadcrumbs ($separator = ' » ', $home = 'Home') { $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); $base_url = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; $breadcrumbs = array("<a href=\"$base_url\">$home</a>"); $last = end(array_keys($path)); foreach ($path AS $x => $crumb) { $title = ucwords(str_replace(array('.php', '_'), Array('', ' '), $crumb)); if ($x != $last){ $breadcrumbs[] = '<a href="'.$base_url.'/'.$crumb.'">'.$title.'</a>'; }else{ $breadcrumbs[] = $title; } } return implode($separator, $breadcrumbs); }
  24. I am pulling some data out of a MySQL database and echoing it out (pretty standard stuff) What is really confusing me is I have checked the query using phpMyAdmin and it returns 1 row which is what i expect. I've even double checked by using a COUNT query and i get the same result. The problem is when I run the returned array through a foreach loop to populate a new array, it appears to create 2 new array rows and i think it's to do with my IF statements. What i want to do in the IF is check is a certain value is present. If not, check that the value is a number and a certain length out of 2 conditions. If not, then do nothing. I'm looking for 3 conditions. Could the problem be that the field type in the database is a varchar and i'm checking for a number? Here is my code $allowed = array('param1', 'param2', 'param3'); //if(isset($_POST['submit'])) { //$sql = 'SELECT consignment_number FROM tracker WHERE order_number = 2893214 AND consignment_number IS NOT NULL'; $sql = 'SELECT column1, column2 FROM table WHERE column1 = :placeholder AND CHAR_LENGTH(column2) > 1'; $stmt = $db->prepare($sql); //$stmt->bindValue('order', $_POST['order']); $stmt->bindValue(':placeholder', $val); $stmt->execute(); $rows = $stmt->fetchAll(); echo count($rows).'<br />'; //echos 1 as checked in phpMyAdmin if(count($rows) != 0) { $myarray = array(); foreach($rows as $row) { $test = $row['column2']; //do something if ($test == 'RM') { // despatched by royal mail $myarray['column1'] = "param1"; $myarray['column2'] = $test; } elseif ( ctype_digit($test) && (strlen($test) == ) { // going by FedEx? $myarray['column1'] = "param2"; $myarray['column2'] = $test; } elseif ( ctype_digit($test) && (strlen($test) == 11) ) { // going by TNT? $myarray['column1'] = "param3"; $myarray['column2'] = $test; } } } else { //no rows } echo count($myarray); echo '<pre>';var_dump($myarray);echo'</pre>'; if(in_array($myarray['column1'], $allowed)) { foreach ($myarray as $array) { if(!empty($myarray['column1'])) { echo $myarray['column1'].': '.$myarray['column2'].'<br />'; } } } else { }
  25. I am importing a text/csv file and instead of importing all of the 'columns' (there are 15 columns on each line), I would like to import column number 1, 4, 15. I have the following code that will import the whole file into an array which works fine but i don't want the whole file in the array becuase I also need to do something like array_unique() where i filter out any duplicates once I have my 3 columns imported into an array. My question is: 1. How do i import the file to only read in the columns i want 2. Once I have all the data into an array , how do i get all the unique rows (so in theory the array size could be halved) Any help greatly appreciated # Open the File. if (($handle = fopen($files, "r")) !== FALSE) { # Set the parent multidimensional array key to 0. $nn = 0; while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) { # Count the total keys in the row. $c = count($data); # Populate the multidimensional array. for ($x=0;$x<$c;$x++) { $csvarray[$nn][$x] = $data[$x]; } $nn++; } # Close the File. fclose($handle); //rename('imports/' . $files, 'archived/' . $files); }
×
×
  • Create New...

Important Information

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