PHP - Update In While Loop Only Adding Last Value And Not All Values
I am trying to get info from a table, add rows in that table, and put the added value back into the table in another field...I want to add field1 and field2 of every row and put the total in the total row. Heres what the echo gives me Susan 14 Mary 18 Bob 13 Sam 21 heres the database mysql> SELECT total_val FROM table; +-----------+ | total_val | +-----------+ | 21 | | 21 | | 21 | | 21 | +-----------+ heres the code.... <?php require("connection.php"); mysql_select_db("database", $connection); echo "<br />"; $result = mysql_query("SELECT * FROM table"); while($row = mysql_fetch_array($result)) { $values = ($row['field1'] + $row['field2']); $sql=mysql_query("UPDATE table SET total = '$values'"); echo $row['user_name'] . " " . $values; echo "<br />"; } ?> also note that if I put a INT in place of $values - the echo changes to match...why?? PLEASE help...I have been working on this for 2 entire days.... Similar TutorialsHi, I have a database with some rows. in each row there is a number such as: 0.0023 or 0.0135... I have the following code to loop though them and add the numbers up but it always returns 0? Code: [Select] $sql="SELECT * FROM tickets WHERE `round` = '$round' AND `confirmed` = 'yes' ORDER BY id ASC"; $result=mysql_query($sql); $row=mysql_fetch_array($result); while($row = mysql_fetch_array( $result )) { $balance = $balance + $row['amount']; } Hope someone can help, I am trying to add up all the values of a variable in a PHP while loop and have tried several approaches but none seem to work. Hopefully someone can point out what the correct method is. I've set up some code to pull the pay rate from a MySQL table, and then calculate that person's earnings based on the amount of time they spend on a particular job. That works fine:
However there may be a number of jobs for different people with different rates, so I want to add all of these up and output the total. So for example if I had values of 125.00, 35.50 and 22.75 I want to show 183.25 as the total. So I tried a few things I found on forums on the subject:
That didn't work so I tried another method that someone suggested:
The 2nd method outputted just the last individual value, the 1st method didn't work at all. Does anyone have a working method that can be used to do this? Thanks Hello Still pretty new to php, so I need a little help with the below code (It's not pretty, but for now I just need it to work correct ) Code: [Select] ... while($row = mysql_fetch_array($result)){ if($row['user_group_id'] <= 2){ $multiplier = 1; } if($row['user_group_id'] == 6){ $multiplier = 2; } if($row['user_group_id'] == 7){ $multiplier = 3; } if($row['user_group_id'] == 8){ $multiplier = 4; } $totalshares = ((($row['activity_blog']*$multiplier)/2)+(($row['activity_comment']*$multiplier)/10)); $set_shares=mysql_query("UPDATE phpfox_user SET bod_shares=$totalshares WHERE profile_page_id=0"); echo " User id: ".$row['user_id']." multiplier:".$multiplier." User group:".$row['user_group_id']." - blog:".$row['activity_blog']." - comment:".$row['activity_comment']." totalshares= ".$totalshares.""; echo "<br />"; } ?> Problem is the UPDATE part "bod_shares=$totalshares", which just inserts "0". How do I get it to update the row with the correct value for each row? The echo shows the right values and calculation for $totalshares. I created a form that would display all the information that was in my database within a textbox using a while loop. The infomation is able to be displayed but when trying to update only the information in the last textbox gets updated and the other textboxes will just stay the same. <?php include ('connection.php'); ?> <form method="post" action="update.php"> <?php $display = mysql_query("SELECT * FROM book ORDER BY id asc") or die("Table Error"); $ID = $_POST['id']; $Title = $_POST['title']; $Cost = $_POST['cost']; $Stock = $_POST['stock']; while ($row = mysql_fetch_assoc($display)) { echo "ID :<input type=\"text\" name=\"".id."\" value = \"". $row['id'] ."\"/readonly>"; echo "Title :<input type=\"text\" name=\"".title."\" value = \"" . $row['title'] . "\"/>"; echo "Cost :<input type=\"text\" name=\"".cost."\" value = \"" .$row['cost'] . "\"/>"; echo "Stock :<input type=\"text\" name=\"".stock."\" value = \"" . $row['stock'] . "\"/>"; mysql_query("UPDATE book SET title = '" .$Title. "', cost = '" .$Cost. "', stock = '" .$Stock. "' WHERE id = '" .$ID. "'"); } ?> <input type="submit" name="update" value="Update" /> Im not sure why it is doing this if someone could tell me it would be a big help Thanks Hi folks... I really didn't know how to title this thread so I hope it makes sense Here is what I am trying to do: Create an editable list of items, price and stock using the 'while' loop - this I can easily do like this... Quote echo "<table width=\"100%\" cellspacing=0>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td width=40% class=item_list>$row[mbp_name]</td>"; echo "<td align=right width=20% class=item_list>"; echo "<input value=\"$row[mbp_price]\" size=\"2\" maxlength=\"5\" type=\"text\" name=\"mbp_price\" /></td>"; echo "<td align=right width=20% class=item_list>"; echo "<input value=\"$row[mbp_stock]\" size=\"2\" maxlength=\"5\" type=\"text\" name=\"mbp_stock\" /></td>"; echo "<td align=right width=20% class=item_list>" . $row['mbp_stock']*$row['mbp_price'] . "</td>"; echo "</tr>"; } echo "</tr></table>"; If I have the update outside the loop then there are only 3 fields that contain a value after the loop is completed ie: mbp_item = the last record name of the table, mbp_price=the last record price and mbp=the last record stock. If I have the update inside the loop the table will update each record but the user may decide to cancel - so then the data in the table is wrong. As an extra feature, I would also be inetersted to know the best way to check that an entered value is valid before the user moves the cursor to a new field? Does anyone have a clue what the best way to do this please? Hi all, I'm trying to figure out how to update values I have in an array. I'm a bit stuck and hope someone can advise. I've read about all sorts of bits but I'm stuck, I dont really understand associative so thought I'd post an example of my code for someone to hopefully assist.. so, if I have a table $fees, which is filled from a select, for example.. select * from `cases_fees`. "contains fields for id, type, amount and others now I want to do is foreach through that table and update a field called `amount`. but I cant understand the foreach >= as key part. what is a key and what isn't ? (I know what the keys of the db table arem but that's not the same eh?) I'm fine with normal foreach, but I cant update back to the array so I need to find out how to be able to set valus back into $fees[`amount`] hope someone can point me in the right direction please... Ted Hi guys, i have a select box which has been populated with values from the database however i would like to be able to select the value from the select box and change the qty. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>stock manager</title> </head> <body> <?php $stockqty =&$_POST['stock_qty1']; ?> <center> <table> <td> <table> <td> <form action='stockview.php' method='POST'> Please Enter a Stock Name and Stock Value <table> <tr> <td> Stock Name: </td> <td> <input name="stock_name" type="text" /><BR /> </td> </tr> <tr> <td> Stock Qty: </td> <td> <input name="stock_qty" type="text" /> </td> </tr> </table> <input name="submit" type="submit" value="Add New Stock Items" /> </form> </td> </table> </td> <td> <table> <td> <form action='stockmanager.php' method='POST' enctype="multipart/form-data"> Please Select from the list the item you wish to update <table> <tr> <td> Stock Name: </td> <td> <?php $connect = mysql_connect("localhost","root", "") or die ("Couldn't Connect!"); mysql_select_db("stock", $connect) or die("Couldn't find db"); // select database $query=("SELECT id, stockname FROM stocks"); $result = mysql_query ($query); echo "<select name=stock value=''>Edit Stock QTY</option>"; while($nt=mysql_fetch_array($result)) { //Array or records stored in $nt echo "<option value=$nt[id]>$nt[stockname]</option>"; /* Option values are added by looping through the array */ } $queryreg = mysql_query("SELECT * FROM stocks WHERE stockqty='$stockqty'"); $numrows = mysql_num_rows($queryreg); $update = mysql_query("UPDATE stocks SET stockqty='$stockqty' WHERE stockname = '$stockname'"); echo("Its updated"); ?> </td> </tr> <tr> <td> Stock Qty: </td> <td> <input name="stock_qty1" type="text" /> </td> </tr> </table> <input name="submit" type="submit" value="Update stock items" /> </form> </td> </table> </td> </table> </center> </body> </html> Any help would be greatly appreciated... ive been working on this for a while and cant seem to find the answer. Thanks Lance I have a code that I am using to update multiple products at one time instead of one at a time. It works great except that my processing page is not updating the very last product. My process page is receiving all of my products as I know how many products that I am updating and I have my process page tell me how many products are updated as well as listing the name of each product updated. It is always the last product that is not updated. Here is my process update code. Code: [Select] <?php $size = count($_POST['casketid']); //$size = 306; $i = 1; while ($i < $size) { $product=$_POST['productid'][$i];//getting case # $price=$_POST['price'][$i]; $model=$_POST['model'][$i]; $active=$_POST['active'][$i]; //Getting pricerange if(($price > "0") && ($price <= "1000.00")) $pricerange = "1"; elseif(($price >= "1001.00") && ($price <= "1500.00")) $pricerange = "2"; elseif(($price >= "1501.00") && ($price <= "2000.00")) $pricerange = "3"; elseif(($price <= "2001.00") && ($price <= "2500.00")) $pricerange = "4"; elseif(($price <= "2501.00") && ($price <= "3000.00")) $pricerange = "5"; elseif(($price >= "3001.00") && ($price <= "3500.00")) $pricerange = "6"; elseif(($price >= "3501.00") && ($price <= "4000.00")) $pricerange = "7"; elseif(($price >= "4001.00") && ($price <= "4500.00")) $pricerange = "8"; elseif(($price >= "4501.00") && ($price <= "4500.00")) $pricerange = "9"; elseif($price >= "5001.00") $pricerange = "10"; $query = "UPDATE products SET price='$price', pricerange='$pricerange', active='$active' WHERE productid='$product'"; mysql_query($query) or die ("Error in query: $query"); echo "$model = $price & active = $active</em><br />$size<br />"; ++$i; } ?> i have the following problem: im trying to update the region_id in citylist2233 according to the region_id in regionlist2233. i can compare regionlist2233.region_name = worldregionlist22.regionname and get the new and old id im messing the loop somewhe Code: [Select] <?php //Insert Unique region id and update $query1 = 'SELECT country_id from worldcountrylist where enable =1 LIMIT 1 '; $results1 = mysql_query($query1); if (mysql_num_rows($results1) > 0) { while($row1 = mysql_fetch_array($results1)) { $query2 = 'SELECT * from citylist2233 where country_id ="'.$row1['country_id'].'" '; $results2 = mysql_query($query2); if (mysql_num_rows($results2) > 0) { while($row2 = mysql_fetch_array($results2)) { //echo $row2['city_id'].''.$row2['city_name'].'-'.$row2['region_id'].'-'; echo $row2['city_name'].'-'.$row2['city_id'].'-'.$row2['region_id'].'<BR>'; $query3='select regionlist2233.region_name ,regionlist2233.region_id from worldregionlist22 LEFT JOIN regionlist2233 on worldregionlist22.regionname = regionlist2233.region_name AND worldregionlist22.region_id <> regionlist2233.region_id AND worldregionlist22.country_id = regionlist2233.country_id WHERE regionlist2233.region_id="'.$row2['region_id'].'" AND regionlist2233.country_id="'.$row1['country_id'].'" '; $results3 = mysql_query($query3); if (mysql_num_rows($results3) > 0) { while($row3 = mysql_fetch_array($results3)) { echo $updatequery='UPDATE citylist2233 SET region_id='.$row3['region_id'].' WHERE region_id='.$row2['region_id'].' AND country_id='.$row1['country_id'].'';}} $update = mysql_query($updatequery) } } } } ?> Hey! How've you been? This should be simple but I can't make it work. I have a few database values from a user entry. The page queries the database and I can print them no problem. I want to add them and display the total of these values. I've tried about two dozen ways of doing and I just can't get them to add. Where I have "fee_total" I want it to be the sum of the values "fee+upgrade7+tax". This is the snippet of what I'm working on. I won't attach any of what I have tried because, well, there are too many attempts and nothing worked $sql = ("SELECT * FROM Teamregister WHERE pkSoloregisterID=$pkSoloregisterID"); $query = mysql_query($sql); $result = mysql_query($sql); $myrow = mysql_fetch_array($result); printf ('<form action="https://www.mysite.com/cgi-bin/webscr" method="post"> <p>Your registration fee is <strong>$%s</strong>.</p>', $myrow['total_fee']); echo ("<input type='hidden' name='item_name_1' value='Registration Fee'>"); printf ('<input type="hidden" name="amount_1" value="%s">', $myrow['total_fee']); echo ("<br /><div align='center'> <input type='submit'' value='Pay Online'> </form>'); Make sense? Like I said, the values are already there but the math isn't happening. To check I tried using individual DB values instead of "total_fee" and the numbers show up. Just cannot get them to add. Hi guys, Im developing a stock system and so far new stock and can be added with the quantity, however im trying to update the stock by using a select box and selecting the type of stock and inputting a new qty. the form and everything is set up and i can select files from the database, however i dont know how to update files from a select box The code i got so far is Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>stock manager</title> </head> <body> <?php $stockqty =&$_POST['stock_qty1']; ?> <center> <table> <td> <table> <td> <form action='stockview.php' method='POST'> Please Enter a Stock Name and Stock Value <table> <tr> <td> Stock Name: </td> <td> <input name="stock_name" type="text" /><BR /> </td> </tr> <tr> <td> Stock Qty: </td> <td> <input name="stock_qty" type="text" /> </td> </tr> </table> <input name="submit" type="submit" value="Add New Stock Items" /> </form> </td> </table> </td> <td> <table> <td> <form action='stockmanager.php' method='POST' enctype="multipart/form-data"> Please Select from the list the item you wish to update <table> <tr> <td> Stock Name: </td> <td> <?php $connect = mysql_connect("localhost","root", "") or die ("Couldn't Connect!"); mysql_select_db("stock", $connect) or die("Couldn't find db"); // select database $query=("SELECT id, stockname FROM stocks"); $result = mysql_query ($query); echo "<select name=stock value=''>Edit Stock QTY</option>"; while($nt=mysql_fetch_array($result)) { //Array or records stored in $nt echo "<option value=$nt[id]>$nt[stockname]</option>"; /* Option values are added by looping through the array */ } $queryreg = mysql_query("SELECT * FROM stocks WHERE stockqty='$stockqty'"); $numrows = mysql_num_rows($queryreg); $update = mysql_query("UPDATE stocks SET stockqty='$stockqty' WHERE stockname = '$stockname'"); echo("Its updated"); ?> </td> </tr> <tr> <td> Stock Qty: </td> <td> <input name="stock_qty1" type="text" /> </td> </tr> </table> <input name="submit" type="submit" value="Update stock items" /> </form> </td> </table> </td> </table> </center> </body> </html> Any help would be greatly appreciated. Thanks Lance Friends, I have the following table:
SELECT * FROM tbl1; +----+-------+-------+ | id | col_1 | col_2 | +----+-------+-------+ | 1 | 1 | NULL | | 2 | 2 | 2 | | 3 | NULL | 3 | | 4 | 4 | NULL | +----+-------+-------+ 4 ROWS IN SET (0.00 sec)So, if I wanna update only the null values of col_2 with these from col_1 or vice versa I'm running the following update statement with mysql ifnull() func. mysql> UPDATE test.tbl1 t1 SET t1.col_2 = ifnull(t1.col_2, t1.col_1), t1.col_1= ifnull(t1.col_1, t1.col_2); Query OK, 3 ROWS affected (0.06 sec) ROWS matched: 4 Changed: 3 Warnings: 0Is there a way to use LEFT JOIN to get all null values from every columns and rows, then to update the columns in the same way? I notice that the sub-query failed for me within an update statement. hello, i have created a table that desplays perticulars, price per person and number of people. the fees is then calculated by multiplying price per person with number of people. till now everything is good. but the problem is when i try to calculate the total fees. here is an example to explain you better: Perticulars Price Per Person Number of people Amount something 10 100 1000 something else 20 100 2000 Total 3000 Code: [Select] $pert_query = mysql_query ("SELECT * FROM `perticulars` WHERE `invoice` =$invoice") or die(mysql_error()); $i = 1; $sum = 0 + $_SESSION['sum']; while($perticulars = mysql_fetch_array($pert_query, MYSQL_ASSOC)) { ?> <tr> <td style="border-collapse: collapse"><div align="center"><?php echo $i; $i++; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['perticulars']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['ppc']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['nop']; ?></div></td> <td style="border-collapse: collapse"><div align="center"> <?php $amount = $perticulars['ppc'] * $perticulars['nop']; echo $amount; $_SESSION['sum'] = $sum+$amount;?> </div></td> </tr><?php } ?> <tr> <td colspan="4" style="border-collapse: collapse"><div align="center">Total</div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $sum; ?></div></td> </tr> </table> From the above code you can see that i am getting the amount form $amount = $perticulars['ppc'] * $perticulars['nop']; by this each row has its own amount which i got by multiplying the data from mysql. the problem is how do i find out the Total. i know i am suppose to add up $amount but how? i even tired using sessions to store the amount and add the new amount to get total but the problem in using sessions is it messes up my next page, no using session is a very bad idea. I'm telling it to add 1 each time through the while loop but its not and not sure why. Code: [Select] <fieldset class="answerLeg"> <legend>Edit Poll Answers</legend> <?php $j = 0; while($row2 = mysqli_fetch_array ( $pollAnswersResult, MYSQL_ASSOC )) { ?> <div class="field required answers"> <label for="answer<?php echo ($j + 1)?>">Answer #<?php echo ($j + 1)?></label><input type="text" class="text" name="answer<?php echo ($j + 1)?>" id="answer<?php echo ($j + 1)?>" title="Answer <?php echo ($j + 1)?>" value="<?php echo $row2['answer']; ?>"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> </fieldset> Hi, I currently have a string with some values in it: $a_random_string="some random text, goes here - $123<br>some more random text goes here - $53 (text 123 )<br>ANother line of text - $126"; Now I want to add all the values that have a '$' before the value eg; $123. So in this case I would end up with: 302 How would I do this? Thanks, mme hello, how would i add the values off all results in the $pamount array? Code: [Select] $result2 = mysql_query("SELECT * FROM pobook WHERE jobnumber = '$jobid'"); while($row2 = mysql_fetch_array($result2)) { $pamount=$row2['amount']; echo "<tr>"; echo "<td>" . $pamount . "</td>"; echo "</tr>"; echo "<tr>"; echo "<td>VALUE OF ALL RETURNED $pamount HERE</td>"; echo "</tr>"; Hey guys: If I some multi-dimensional arrays, like so: Code: [Select] array { array { [0]=> "Path1" [1]=> "10" } } array { array { [0]=> "Path2" [1]=> "16" } array { [0]=> "Path3" [1]=> "110" } } How can I add all of the values of key 1? I know its a foreach loop, but I can't figure it out... would it be this? I have the following multidimensional array where each sub-array represents quantity[0] and item #[1]: Array ( => Array ( => 1 [1] => 12113 ) [1] => Array ( => 2 [1] => 21200 ) [2] => Array ( => 4 [1] => 10200 ) [3] => Array ( => 1 [1] => yyyy ) [4] => Array ( => 20 [1] => xxxxx ) [5] => Array ( => 5 [1] => 21200 ) I'm trying to consolidate like items. For example I need to create a new array that reflects any duplicate part numbers with a combined quantity. (ie. ... => 7 [1] => 21200 ... Code: [Select] $product_id=$_GET['product']; $sql500="SELECT * FROM $tbl_name3 WHERE product_id='$product_id'"; $result500=mysql_query($sql500); $num_rows500=mysql_num_rows($result500); while($row500=mysql_fetch_array($result500)){ extract($row500); $review_product_rating_total=$review_product_rating; //What do I do here? } $average_rating=$review_product_rating_total/$num_rows500; I need a way to take a column of product ratings (0-5 in 1/2 increments), add them together, and divide by the number of rows taken from the database. I know how to get the number of rows with mysql_num_rows. But how would I add together the data from database? I have a store number that i want to add and echo. This resembles an invoice so i my table has unit_price and total_value which is defined by by multiplying unit_price and pieces. Now that i want to print invoice i want to know how to add all items that are from that invoice_id Code: [Select] //get the total value for order $sql_value = "SELECT total_value FROM `".TABLE_ORDERDETAILS."`WHERE order_id = $record_order[order_id]"; $rows_value = $db->fetch_all_array($sql_value); foreach($rows_value as $record_value){ $value = $record_value[total_value]; } |