PHP - Foreach And Updating
Okay lets say after the form submission I have this inside the post parameters.
answersList Undisputed Title2:::5,Outlaw Title3:::6,Tag Team Titles4:::7 If you see I have it exploding the list at the "," character. Then what I want to happen is for it to take out the ":::" characters and create a variable called $answerID for the number after the ":::" and then have it be able to run through the UPDATE query so that it UPDATES the old value with the new value. Code: [Select] $answer = explode(',', $_POST['answersList']); foreach ($answer as $answer) { $answer = htmlspecialchars($answer); echo $answer; $query = "UPDATE `pollAnswers` SET `answer` = '".$answer."' WHERE `ID` = '".$answerID."'"; mysqli_query($dbc, $query); echo $query; } Similar TutorialsI can get the info from the database fine with this: Code: [Select] $sql2 = "SELECT 1, 2, 3, 4, 5, 6 FROM ratestable ORDER BY id ASC"; $stmt2 = $db->prepare($sql2); $stmt2->execute(); $e2 = $stmt->fetch(); and display it with this: Code: [Select] <?php while($e2 = $stmt2->fetch()) { ?> <input type="text" name="1" maxlength="10" value="<?php echo $e2['1'] ?>" class="rates" /> <input type="text" name="2" maxlength="10" value="<?php echo $e2['2'] ?>" class="rates" /> <input type="text" name="3" maxlength="10" value="<?php echo $e2['3'] ?>" class="rates" /> <input type="text" name="4" maxlength="10" value="<?php echo $e2['4'] ?>" class="rates" /> <input type="text" name="5" maxlength="10" value="<?php echo $e2['5'] ?>" class="rates" /> <input type="text" name="6" maxlength="10" value="<?php echo $e2['6'] ?>" class="rates" /> <?php } ?> How do I update it to the database? Code: [Select] $sql = "UPDATE rates SET title1=?, title2=?, title3=?, title4=?, title5=?, title6=? THE CODE HERE IS WHERE I AM STUCK.... and that's as far as I can get, need to use an array or foreach??????? [/quote] This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 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'm back, I have a code that based on my understanding should work, but needless to say doesn't <?php $sql ="select * from `piprice`"; $result = mysql_query($sql); $count = mysql_num_rows($result); echo "<table border=1><tr><td>Product Name</td><td>Item ID</td><td>Price</td><td>Enabled</td>"; echo "<form action=main.php?id=test1.php method=post>"; while ($row = mysql_fetch_array($result)) { echo "<tr><td>".$row['product name']."</td>"; echo "<td>".$id[] = $row['item id'];$row['item id']."</td>"; echo "<td>".$row['price']."</td>"; $enabled[] = $row['enabled']; echo"<td><select name=".$enabled.">< <option Value=".$row['enabled'].">".$row['enabled']."</option> <option Value=Yes>Yes</option> <option Value=No>No</option> /select></td</tr>"; } echo "<input name=submit type=submit value=Update>"; echo "</form></table>"; if(isset($_POST['submit'])) { for($i=0;$i<$count;$i++){ $sql1="UPDATE `piprice` SET `enabled` = '$enabled[$i]' WHERE `item id` ='$id[$i]'"; $result1=mysql_query($sql1) or die (mysql_error()); } } ?> Basically I want to be able to pick yes/no and have it update in the database. One a side note is there a good site for me to learn php on (I just know the basics) besides asking 101 questions here So, I am making a CMS for my school and I am having some trouble. It's a magazine sort of CMS and what I want is that when you click on a certain thing it continues onto the next page. Through the CMS you can create pages - when you do this each page gets a unique PID. To access the pages you have to enter the PID on the end of the URL, e.g. : http://www.myschool.com/magazine/index.php?pid=x. What I need is a code that when an image gets clicked the PID number in the URL goes up by one. Thanks Hi, I'm using php to access the mysql database using mysqli and I have a field on my table called "timestamp" and it's set as a timestamp and has current_time (I think in phpmyadmin it was a tick option so I clicked it) and when I update that row in my table the field "timestamp" doesn't update with the timestamp from when it was last updated/modified. I thought the field option timestamp automatically did that? I'm guessing not.. is there a way I can update the timestamp with the current time in my query? $query1 = "select * from movies where title = '".$title."' ;"; $result1 = mysql_query($query1) or die('Could Not Execute The Query'); while ($row = mysql_fetch_assoc($result1) ) { for($f=0; $f<$parts[$current_k]; $f++ ) { touch("$base_folder/{$hos}/".$linking[$sum].".php"); $old_part_href = $row['href_parts']; $updated_part = $old_part_href.$new; $query_href = 'update movies set href_parts = \''.$updated_part.'\''; mysql_query($query_href) or die('COULD NOT EXECUTE THE QUERY FOR PARTS HREF'); $new = "{$base_folder}/{$hos}/".$linking[$sum].".php"; $sum++; } } what i am trying to do is take the value of href_parts and add the new href of the page to the existing value on the href_parts and update the href_parts field in my db.. but i am not getting the desired results.. all i am getting in the db is the last value that is passed in the loop in the db.. i want to save the values which are exisiting in the db and add the newly created values to itt.. can anyone help please.. $sqld = "SELECT * FROM orders WHERE `id`='$delete' AND `name`='$inf2[name]' AND `email`='$inf2[email]' LIMIT 1"; $csql = $db->query($sqld); $ccheck = $csql->fetch(PDO::FETCH_NUM); $cinf = $csql->fetch(PDO::FETCH_ASSOC); $quantity = $cinf[quantity]; $code = $cinf[code]; $stmt11 = $db->prepare('UPDATE feeds SET quantity=quantity-:quantity WHERE code=:code'); $stmt11->bindValue(':quantity', $quantity, PDO::PARAM_STR); $stmt11->bindValue(':code', $code, PDO::PARAM_STR); $stmt11->execute(); $id = $delete; $name = $inf2[name]; $stmt2 = $db->prepare("DELETE FROM orders WHERE id=:id AND name=:name"); $stmt2->bindValue(':id', $id, PDO::PARAM_STR); $stmt2->bindValue(':name', $name, PDO::PARAM_STR); $stmt2->execute();OK, i have just been told i should start using PDO instead of mysql to update my tables. This code works to delete the order but doesn't update the feeds section. All this is new to me so far and i think i am getting the hang of it. Should i still be using the quantity=quantity-:quantity or is there another way to do it with PDO? Sorry, i posted this in the wrong forum. Hope someone here can help until it's moved Edited by Self_Taught_Still_Learning, 30 May 2014 - 03:30 PM. In the code I want to proceed to the next step only after stripslashes and strip_tags are completed. How do I put the code below with if? $stripped = array('name', 'location', 'bio'); foreach ( $_POST as $k => $v ) { if ( in_array($k, $stripped) ) { ${$k} = strip_tags($v); } } foreach ( $_POST as $p => $q ) { if ( in_array($p, $stripped) ) { ${$p} = stripslashes($q); } } Thanks, Ruth. Hi! When I echo $m below, it will show all selected options fine. Instead, I want it to show many I selected. So if I selected 3 in dropdown, I want it to say I selected 3 instead of showing their values. $allmaps=$_POST['maps']; foreach ($allmaps as $m) { echo 'm = '.$m.''; } <select name="maps[]" multiple>'.$maps.'</select> I'm trying to figure out why its saying Warning: Invalid argument supplied for foreach() in /home/content/y/a/n/yankeefaninkc/html/defiant/efedmanager/forms/booking.php on line 17. I thought I did the foreach loop right so far. $eventid = $_GET['id']; $query = "SELECT CONCAT_WS(' ', eventnames.eventname, events.label) AS event, DATE_FORMAT(events.bookingdate, '%M %d, %Y') AS bookingdate, events.nummatches AS nummatches FROM events, eventnames WHERE events.event_id = eventnames.id AND events.id = '" . $eventid . "'"; $result = mysqli_query ( $dbc, $query ); // Run The Query foreach ($nummatches as $matchnum) { echo "Match # $matchnum"; echo "<select class=dropdown name=matchtype id=matchtype title=Match Type>"; echo "<option value=0>- Select -</option>"; $query = 'SELECT id, matchtypename FROM matchtypes'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['matchtypename']."</option>\r"; } } I am trying to develop a calendar. I have code to determine the number of days for each month. I want to cycle through each day and spit out code for each day. Something like the following: Code: [Select] <?php $month = "December"; $days = 31; foreach($days){ echo "<div id='day_block'> ".$days." </div>"; } ?> i think i need to use a counter but don't know how, any help would be awesome! why does wordpress is using foreach rather than while in listing records? common Code: [Select] while ($products = mysql_fetch_object($rs) { ... } but wordpress is using foreach Code: [Select] foreach ($posts as $post) { ... } which is better? because i'm trying to create my own code for database connection. public function update($data, $table, $where) { foreach ($data as $column => $value) { $sql = "UPDATE $table SET $column = $value WHERE $where"; print "table: ".$table." column: ".$column." whe ".$where; mysql_query($sql) or die(mysql_error()); } return true; } $data: $data = array( "username" => "Jack", "email" => "jack.gmail@gmail.com" ); $db->update($data, "users", 'id=1'); Working on this code that updates a column from a class. Everything is fine except for one issue. As of right now $column is set to "Jack" which outputs an error, instead of what it should be as "username". I'm sure it's something really simple, so any assistance is appreciated. Any ideas? Problem area is listed in red. Hi All, I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each property that is associated with the search: <ul> <?php foreach($properties as $property) { ?> <li><?=$property->$zipcode?></li> <?php } ?> </ul> How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code? Thanks in advance! P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors. Anyways, thanks in advance for the help! Hi can any one help please im still very new but hard trying The problem is that i only get 1 result back from the database i need it to loop any ideas please Code: [Select] $query = mysql_query("SELECT * FROM categorys, sub_categorys WHERE categorys.cat_id = sub_categorys.cat_id"); echo "<ul>"; $row[] = mysql_fetch_array($query); foreach($row as $category){ echo "<li>"; echo $category['category']; foreach($row as $sub_category){ if($category['cat_id'] == $sub_category["cat_id"]){ echo "<ul><li>".$sub_category["sub_category"]."</li></ul>"; } } echo "</li>"; } echo "</ul>"; Hi i am trying to pass values from a cart to a database using foreach. This is my code: Code: [Select] $columns = array('order_id', 'order_item_id', 'order_product_name', 'order_product_dimensions', 'order_product_options', 'order_product_quantity', 'order_product_price', 'order_product_subtotal', 'order_product_vat', 'order_product_delivery','order_product_total','order_product_sku','order_product_image_name','order_product_image_type','order_product_image_path','order_product_image_size','order_product_artwork_link','order_product_artwork_name','order_product_artwork_type','order_product_artwork_path','order_product_artwork_size','order_firstname','order_lastname','order_companyname','order_email','order_tel','order_billing_address','order_billing_address2','order_billing_town','order_billing_county','order_billing_postcode','order_shipping_address','order_shipping_address2','order_shipping_town','order_shipping_county','order_shipping_postcode','order_status','order_username'); $data = array_fill_keys($columns, 'NULL'); foreach($data as $key => $value) { $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_escape_string($_POST[$key])."'"; $query = "INSERT INTO orders (id, order_created_at, ".implode(", ",$columns).") VALUES (null, NOW(), ".implode(",",$data).')'; } Problem is posting 2 or more products into the database. How do i split the values so it enters each product into the database? Noob question. I've learned so much in the last couple of weeks that I've actually found two ways of doing the same thing! I was wondering which was the better method, if there is any difference. They are being used to print somewhere between 10 and 200 lines of text. Either: $categories_count= (count($categories[1])) -1; for ($u=0; $u < $categories_count; $u++) {echo "<li>".$categories[1][$u]."</li>";} Or: foreach ($categories[1] as $line => $cat) {echo "<li>".$cat."</li>";}; today i programmed my own weight calculator. one thing i am having a problem is with trying to make it so if a weight is over a certain number, then the shipping price will increase by X. shipping prices are charged in 20000 gram blocks, so if I have something that is 22000 grams then that will be two blocks. what i need to do is something like (this is a big guess) Quote $row3 = 50; $weighttotal = 22000; if ($weighttotal > 20000) { foreach (20000) { $row3 += $row3;} } } } can it be done on php?? I appear to be having a simple simon day! my foreach is only displaying the last result in the table as opposed to each row $num_rows = mysql_num_rows($query); echo "There are $num_rows records.<br>"; while($row = mysql_fetch_row($query)) foreach ($row as $field) { echo '<div class="results">'; echo $field; echo '<br></div>'; } And the source Code: [Select] <link href="../styles/clientbox.css" rel="stylesheet" type="text/css"> <body><br> <h3>My Services</h3> <div class="text"> You currently have the following services with us: </div> There are 2 records.<br><div class="results">test1<br></div> </body> </html> My table has 2 rows which the 1st one has a package of test and the second a package of test1 Can anyone help? Thanks |