PHP - Foreach Question In An Array Of $_session
I am having trouble understanding what this means:
foreach($_SESSION['cart'] as $product_id => $quantity) I look forward to any responses in advance. Similar TutorialsHey all, I'm well aware of associative arrays (key/value pairs) and how you can index them in an array like this: $character = array (name=>"John", occupation=>"Programmer", age=>22, "Learned language "=>"PHP" ); Then it makes sense to iterate through the key/value pairs of the array using foreach: foreach ( $character as $key=>$val ){ print "$key = $val<br>"; } However, I was watching a video tutorial where he created a $_SESSION array and then created an array associative array: $_SESSION['cart'] = array(); [/PHP] Then he added a function add_to_cart: function add_to_cart($id){ if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]++; return true; } else { $_SESSION['cart'][$id] = 1; return true; } return false; } Now that $id variable holds an id converted to integer from the dataabse. So if first item is clicked, id holds a value of integer 1. When I see this: $_SESSION['cart'][$id] I see an array that holds two indexes, each index containing an associative array: [[array() => ''], [1 => '']]. So at index 0 of $_SESSION is [array() => '']. But then he uses the foreach iterator like this: function total_items($cart){ $items = 0; if(is_array($cart)){ foreach($cart as $id => $qty){ $items += $qty; d } } return $items; } Now I'm very confused. As you can see in that foreach method, it says that $id (and its corresponding value) is an associative array of $cart array, not $_SESSION array. I don't see how that happened. I thought $cart and id$ were distinct indexes of $_SESSION. I don't see how $id is a key of the $cart array. Thanks for any explanation to clear my confusion. hey guys! Im trying to get hashtags out of a string. The function works so far- but i cant transfer the insides of the preg_match_all array into the string. A hint would be fine already. Thanks in advance- and here is some code Code: [Select] <?php //example string $strcontent = "ima string... #wat #taggy #taggytag im in your stringz, stealing your charz!"; //find hashtags preg_match_all("/(#\w+)/", $strcontent, $matches); echo $matches; //the output is just "array" -> why? foreach ($matches as $match) { // $tempmatch=$match[1]; #####like this? //hiding the hashtags via span $strtemp="<br>ima span<br>" . $match . "<br>ima /span<br>" . $strcontent; $strcontent = $strtemp; echo $strcontent; } #echo $strcontent; # <span style="display:none;"></span> ?> I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } I just got through a server problem with a variable named $_SESSION['id'] What would happen was when I loaded a mysql request with id in it (usually what i name the main key in a table) it would overwrite the value in the $_SESSION without specifically asking it to ie $_SESSION['id']=$id; This was on an acenet server I have the same thing on a bluehost server and wampserver and never had a problem What I did on acenet was rename $_SESSION['id'] when declaring it to $_SESSION['usernumber'] and all my issues stopped Anyone know why? Is it a acenet problem? My problem is fixed im just wondering if anyone has had a similar issue????? Hi all, I have a set of checkboxes which I need to be able to send into a session, which can be picked up later but exploded (it could be a possible maximum 7 options, may be only be 1). I've been experimenting with foreach, but I can't get that into a session to be able to reuse, only $_POST which can't be carried over different pages. Also, once I have them inside a session, how do I print what's been selected (rather than having to pick out manually). IE - so if six have been selected, it prints those six options, or if it's two then it prints just those two choices. Thanks! Jason
First let me explain my code. This is later included in project_status.php] . In project_status.php] , I have included another file project_status_app.php which contains a HTML form.
<?php include 'inc_fn_header_and_menu.php'; function includeFile($file,$variable) { $var = $variable; include($file); } if (isset($_GET['id']) && $_GET['id']!="") { $pid = $_GET['id']; $_SESSION['pidForApproval'] = $_GET['id']; $query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\''; $result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n" . mysqli_error()); foreach ($result as $row) { $status = $row['status']; } } ...........some PHP and HTML code....... <div id="customerPurchaseApprovalForm"> <?php echo '<p>APPROVAL FOR CUSTOMER PURCHASE</p>'; $discountApprovalStatus = "Granted"; if ($discountApprovalStatus == "Granted") { includeFile("project_status_app.php",$highestannualvalue); } else { //......... } In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array. <?php // put your code here UPDATE `pp` SET `customer_purchase_remarks` = 'hahaha' WHERE `pp`.`id` = 207; if ($_SERVER['REQUEST_METHOD'] == 'POST') { include '../../inc/fastlogin.php'; $sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'"; $result = mysqli_query ( $fastdb, $sql ) ; if (mysqli_affected_rows($fastdb) != 1) { $_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>"; //echo "<p>Error while updating WHERE id='{$_POST['pidForApproval']}'</p>".mysqli_error($fastdb); } else { $_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>"; //echo "Records was updated successfully."; } header ("location: project_status.php?id="$_SESSION['pidForApproval']); exit(); } ?> When I load project_status.php, project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the header ("location: project_status.php?id=".$_SESSION['pidForApproval']);
Missing some information. Can anyone tell me why Count(ID) is not counting correctly? I want it to count how many entries in the database for each agent but its saying 28 prospects, 0 insureds when it should be 1 prospect, 5 insureds for the time frame i selected. foreach($emplist as $emplists){ $prospc = mysql_query("SELECT Count(ID) FROM clients WHERE agentname = '$emplists' AND Status = 'Prospect' AND Agency = '$agency'") or die(mysql_error()); $prospcount = mysql_fetch_assoc($prospc); $prospects = $prospcount['Count(ID)']; $insuredc = mysql_query("SELECT Count(ID) FROM clients WHERE agentname = '$emplists' AND Status = 'Insured' AND Agency = '$agency'") or die(mysql_error()); $inscount = mysql_fetch_assoc($insuredc); $insureds = $inscount['Count(ID)']; } Hi There, is there any way to not print last <br> on screen with foreach. Code: [Select] $letters = array('a','b','c'); foreach($letters as $letter) { echo "$letter <br />"; } as html output a<br /> b<br /> c I have a foreach function within my website, it is used as part of a search engine i have created. The code was working and then i restarted my computer and now the code is not working. The code uses the explode function to separate each search term into an array. And then if there is more than one search term it adds a extra line of code onto the SQL query. If anyone could tell me why this is not working that would be a great help. Code: [Select] $search_exploded = explode(" ",$search); $x = 0; foreach($search_exploded as $search_each) { $x++; if ($x==1) $construct .= "keywords LIKE '%$search_each%'"; else $construct .= " OR keywords LIKE '%$search_each%'"; } $construct = "SELECT * FROM products WHERE $construct"; Thanks Boldonglen Edit: I forgot to mention that what is happening is when i search for more than one term it is just showing the "SELECT * FROM products WHERE keywords LIKE '%$search_each%'" and not the OR statement. The $search_each is showing both the search results but just taking away the space. Hello everyone, I am working on a form that is similar to a shopping cart system and I am thinking of creating a button that submits the checked value and saves them to a $_SESSION variable. And also a link that links to a cart.html that takes the values of a $_SESSION variable. I am have trouble figuring what tag/attribute should I use in order to achieve that.
Right now my code attached below submits the checked values to cart.html directly. However I want my submit button to save the checked box to a $_SESSION variable and STAY on the same page. And then I will implement a <a> to link to the cart.php.
I researched a little bit about this subject and I know it's somewhat related to ajax/jquery. I just wanted to know more about it from you guys. I appreciate your attention for reading the post and Thanks!
Below is the form that I currently have:
<form name= "finalForm" method="POST" action="cart.php"> <input type="Submit" name="finalSelected"/> <?php foreach($FinalName as $key => $item) {?> <tr> <td><input type="checkbox" name="fSelected[]" value="<?php echo htmlspecialchars($FinalID[$key])?>" /> <?php echo "$FinalID[$key] & $item";?> </td> </tr> <?php } ;?>Below is the code for cart.php <?php require ('connect_db.php'); if(isset($_POST['finalSelected'])) { if(!empty($_POST['fSelected'])) { $chosen = $_POST['fSelected']; foreach ($chosen as $item) echo "aID selected: $item </br>"; $delimit = implode(", ", $chosen); print_r($delimit); } } if(isset($delimit)) { $cartSQL = "SELECT * from article where aID in ($delimit)"; $cartQuery = mysqli_query($dbc, $cartSQL) or die (mysqli_error($dbc)); while($row = mysqli_fetch_array($cartQuery, MYSQLI_BOTH)) { $aTitle[] = $row[ 'name' ]; } } ?> <table> <?php if(isset($delimit)) { $c=0; foreach($aTitle as $item) {?> <tr> <td> <?php echo $aTitle[$c]; $c++;?> </td> </tr> <?php }}?> </table> What I' trying to do is take my array Code: [Select] $stores = array("name"=>"$MktName","address"=>"$address"); And for each each value, insert it into my db Code: [Select] foreach($stores as $k => $v){ mysql_query("INSERT INTO stores (name, address) VALUES('$k', '$v' ) ") or die(mysql_error()); } Now, I'm just learning more about arrays, and this is obviously wrong How do I go about getting the value of "name"? It pulls the value for "address". Thanks in advance I got this already, my problem is I can't get all values of my $prog array because of '=>' operator. Is there any way to get rid of this? Code: [Select] foreach ($_POST['course'] as $val =>$course) { $prog = $_POST['program'][$val] ; echo $course; echo $prog; } I have the following foreach statement that gets the error msg's from the array called errors. However for the last key in the array, i would not like the <br /> to be echo'd out. How can I achieve that? Code: [Select] foreach ($errors as $msg) { echo $msg; echo "<br />"; } Hi guys,
Having trouble trying to show values from my $friend array. Only the first friend code is being displayed in my output.
There are several fields in my mysql associated with the $sql.
Any ideas?
Thanks
$sql = "SELECT * FROM friends WHERE Code = '$code' OR FriendCode = '$code' AND Status ='A'"; $result = mysqli_query($cxn,$sql) or die ("Can't get friends."); $friend = array(); while($row=mysqli_fetch_array($result)) { if($code == $row['FriendCode']) { $friend[] = $row['Code']; } elseif($code == $row['Code']) { $friend[] = $row['FriendCode']; } foreach($friend as $key => $value) { echo $value.'<br />'; } Edited by unistake, 18 June 2014 - 06:13 AM. Hi, I have an array: Code: [Select] Array ( [0] => index.php [1] => Home [2] => page.php?id=23 [3] => Page ) How would I loop through it so I can link the previous value to the next value within the array e.g.: Code: [Select] <a href="index.php">Home</a> <a href="page.php?id=23">Page</a> hello. i have a foreach loop thats pulling out information that i dont want. how do i stop it. this is the loop Code: [Select] //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } the loop sits inside this function which has more loops Code: [Select] function listNavText($PHGlidA, $PHLobA, $PHLodA){ //GET THE LANGUAGE $langBS = basicSettings::find_by_id(1); $langID = $langBS->language_id; //GET THE LIST ORDER $PHLoa = PhLists::find_by_order($PHGlidA, $PHLobA, $PHLodA); foreach ($PHLoa as $PHLoas){ $PHLidA = $PHLoas->id; //GET THE LIST TEXT IDS $PCba = PCbridge::find_by_list($PHLidA, $langID); foreach ($PCba as $PCbas){ echo $PCidA = $PCbas->pageContent_id; //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } } } } this is what it echoes out 105L1-Title1 118 116 114 112 110 108L2-Title4 111 109L2-Title5 113 115 117 106L1-Title2 119 107L1-Title3 the number at the start is the text id L1-Title1 to L1-Title5 are tiles ($title) the spaces are links ($links) the problem is that i don't want the link spaces showing. just the 5 titles thanks Hello guy, Just wanted to see how I could resolve this issue I have a foreach loop here that will spit out the vars. Code: [Select] foreach (array_keys($_POST) as $key) { $$key = $_POST[$key]; print "$key is ${$key}<br />"; } echo "<br><br><br>This is the viewname" . $viewname; echo "<br><br><br>This is the price" . $price; I am trying to run the post vars through a filter (The filter name is filter($value) but I cant get it to work. I tried this Code: [Select] foreach (array_keys($_POST) as $key) { $$key = $_POST[$key]; $$key = filter($value); print "$key is ${$key}<br />"; } echo "<br><br><br>This is the viewname" . $viewname; echo "<br><br><br>This is the price" . $price; Any ideas? Thanks, Dan Hello Guys, I have a question. I have the following code to grab all of my $_POST vars and run through my filter function Code: [Select] foreach($_POST as $key => $value) { $mydata[$key] = filter($value); } Before using the foreach loop I was just doing the basic $var1 = $_POST['var1']; $var2 = $_POST['var2']; I'm going to have about 40 - 50 $_POST vars so my question is how do i return it as just a $var name instead of having to do this echo "<br><br><br>example1" . $mydata['var1']; echo "<br><br><br>example2" . $mydata['var2']; I guess its hard for me to explain.. Thanks for your help! Hello gurus, I've been pounding my head against the wall on this one. It must be something simple I'm missing. I have a text field that posts ($_POST['case_ids']) a comma separated value such as 10067,10076 When I use explode to break it up it should make it an array. However when I use it in a foreach loop I get an invalid argument error. If I do a check for is_array() it fails the check. If I print the array I get: Code: [Select] Array ( [0] => 10067 [1] => 10076 ) So I thought maybe I get the error because the individual array elements don't have commas between them so I wrote this to put commas in between each element except the last: Code: [Select] $cases = array(); $numItems = count($case_ids);//get count of array $i = 0;//initialize counter foreach($case_ids as $key => $value){ if($i+1 != $numItems) { $cases[$key] = $value.','; }else{ $cases[$key] = $value; }//end if $i+1 $i++; } However this new array still gets the invalid argument error. Are these not valid arrays? Any help would be greatly appreciated. Thanks in advance, Twitch |