PHP - Php Update With While Loop
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 Similar TutorialsHi 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? 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 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) } } } } ?> 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.... This way seems not good. <?php $username ="MANCENT"; $user_input_x = _xmouse.movement ;//FLASH $user_input_y = _ymouse.movement ;//FLASH while(true) { $updatepos = mysql_query("UPDATE users_float SET user_input_x = '$user_input_x' , user_input_y = '$user_input_y' WHERE username = '$username'"); } This way works but whats a better way? ?> I am trying to create a quick script to update all my products in my product table, I want to set a prodOrder starting at 1 and incrementing by 1 for each product in the catalogID group. eg if I have 12 product with a catalogID of 1 then I want to number the prodOrder for each product in my table 1-12 and so on for each catalogID group whats the best way to do this here is my starter code but no where near performing this function $sql=("SELECT * FROM product ORDER BY productID ASC GROUP BY catalogID"); $result=mysql_query($sql); while($row=mysql_fetch_array($result)) { $catID=$row['catalogID']; $id=$row['productID']; $value='1'; foreach ($catID AS $id => $value) { $qty=("UPDATE product SET prodOrder='$value' WHERE productID='$id'"); $change=mysql_query($qty); echo $row['name']." from $catID - order = $value<br/>"; $value++ } } Hi there, hope have some help. I have a form where a user select time and days of the week (monday, tuesday..) that he is available. The insert script works fine, it insert and the days of week he checked in the table, the only problme is when i try to update each of them.
I used this code above, but is not working, instead of updating/inserting days that is selected is inserting multi-records with the same day of the week value.
here it is:
foreach($weekDay as $DaysofWeek){ $sql_days = "UPDATE available SET day_time = '$day_time', week_day = '$DaysofWeek' WHERE user_id = '$id_user'"; $update_availability = mysql_query($sql_days); } This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=321230.0 I have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
Can anyone post a generic update function to update mysql table. The manual approach: update $tablename set $column1='a', $column2='b' where $id=$value; Hi i have this simple update form and scrip but somehow it doesnt seem to be update the field on the database can someone help out please. The html form is the second form bellow where the action send to status_update.php HTML FORM Code: [Select] <?php include("../header.html"); ?> <?php include("header_news.html"); extract($_REQUEST,EXTR_SKIP); ?><?php /* print("sfilm_refnum = $sfilm_refnum<BR>"); print("sfilm_addr01 = $sfilm_addr01<BR>"); print("sfilm_postcode = $sfilm_postcode<BR>"); print("Film Client = $fclient<BR>"); */ ?> <form id="search" action="list.php" method="post" name="search"> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td align="right" width="140"></td> <td width="320"><span class="hofblack10"> </span> </td> <td align="center" width="100"><input type="hidden" name="lstart" value="<?php print("$lstart"); ?>" /><input type="hidden" name="lend" value="<?php print("$lend"); ?>" /><input type="hidden" name="lamount" value="<?php print("$lamount"); ?>" /></td> <td align="center" width="100"></td> <td align="right"></td> </tr> </table> </form> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#4050c4"> <tr> <td width="60" class="hofwhite10">action</td> <td width="140"><span class="hofwhite14">DATE</span></td> <td width="80"><span class="hofwhite14">ID</span></td> <td><span class="hofwhite14">News Titile</span></td> <td width="100"><span class="hofwhite14">Status</span></td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table><table width="780" border="0" cellspacing="0" cellpadding="4"><tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> <tr height="0"> <td width="60" height="0"></td> <td width="80" height="0"></td> <td height="0"></td> <td align="right" width="120" height="0"></td> </tr> </table> <?php //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select DATABASE."); $query2="SELECT * FROM news WHERE !(news_status='deleted')"; $result2 = mysql_query($query2) or die("Couldn't execute QUERY - Select NEWS Qty"); $fqty = mysql_num_rows($result2); //SELECT or FIND the same USERNAME $query3="SELECT * FROM news WHERE !(news_status='deleted') ORDER BY news_id DESC"; $result3 = mysql_query($query3) or die("Couldn't execute QUERY - Select NEWS"); while ($row = mysql_fetch_array($result3)) { $news_id = $row['news_id']; $news_title = $row['news_title']; $news_story = $row['news_story']; $news_image = $row['news_image']; $news_image_caption = $row['news_image_caption']; $news_image_link = $row['news_image_link']; $news_date_day = $row['news_date_day']; $news_date_month = $row['news_date_month']; $news_date_year = $row['news_date_year']; $news_status = $row['news_status']; $news_website = $row['news_website']; $news_date_created = $row['news_date_created']; $news_date_modified = $row['news_date_modified']; ?> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td width="60"><span class="hofblack10"> <?php if($news_status=="deleted"){ print("<a class='hifblack10'>deleted</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>edit</a>"); } ?> </span></td> <td width="140"><span class="titlegrey12"> <?php if(!$news_date_day) { echo "00"; } else{ echo $news_date_day; } echo "/"; if(!$news_date_month) { echo "00"; }else{ echo $news_date_month; } echo "/"; if(!$news_date_year) { echo "0000"; }else{ echo $news_date_year; } ?> </span></td> <td width="80"><span class="titlegrey12"><?php print("$news_id"); ?></span> </td> <td><?php if($news_status=="deleted") { print("<class='hofblack10'>$news_title</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>$news_title</a>"); } ?></td> <td width="100"> <form id="list_update" action="status_update.php" method="post" name="list_update"> <select name="newnstatus" size="1"> <option <?php if($row['news_status'] == "") { print("selected"); } ?> selected="selected" value="">Status...</option> <option <?php if($row['news_status'] == "on") { print("selected"); } ?> value="on">On</option> <option <?php if($row['news_status'] == "off") { print("selected"); } ?> value="off">Off</option> <option <?php if($row['news_status'] == "deleted") { print("selected"); } ?> value="deleted">Delete</option> </select> <input type="hidden" name="nstatus" value="<?php echo $row[news_status]; ?>" /> <input type="hidden" name="id" value="<?php echo $row[news_id]; ?>" /> <input type="submit" name="update" value="update" /> </form> </td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table> <?php } mysql_close($connection);//}?> <table width="780" border="0" cellspacing="0" cellpadding="4"> <tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> </table><?php // include("list_navigation.html"); ?> <?php include("../footer.html"); ?> </div></body></html> The action script php Code: [Select] <?php /* echo "fstatus: ".$fstatus."<BR>"; echo "id: ".$id."<BR>"; echo "fclient: ".$fclient."<BR>"; echo "newfstatus: ".$newfstatus."<BR>";*/ //set the date of agreement $timestamp = date('l jS \of F Y h:i:s A'); //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select FILMS DATABASE."); // All appears well, so enter into database $query= "UPDATE news SET news_status = '$newnstatus' WHERE news_id='$id'"; $result = mysql_query($query) or die("could not execute query - Update FILMS Record to DB"); //setup an email to the Admin @ hof, w/o attachment $emailto="xx@xxx.co.uk"; $emailfrom="no-reply@xxxx.co.uk"; $emailsubject="xx Record Updated"; $emailmessage="Hello Registrar\n\n"; $emailmessage.="News ID: ".$id."\n"; $emailmessage.="Updated on: ".$timestamp."\n\n"; $emailmessage.="Status was: ".$nstatus."\n"; $emailmessage.="Status now: ".$newfnstatus."\n"; $emailmessage.="Thank you,\n\n"; $emailmessage.="Web Site ROBOT\n"; $emailmessage.="(Administrator)\n"; $emailmessage.="xxx.co.uk | xxx.biz\n"; $emailmessage.="----------------------------------------------\n"; $emailmessage.="e. http://www.xxx.co.uk/contact.php\n"; $emailmessage.="w. http://www.xxx.co.uk\n"; $emailheader="From: xxx.co.uk<$emailfrom>"; $emailheader .= 'Cc: xxx@xxx.co.uk'."\r\n"; $emailheader .= 'Bcc: xxx@xxxxx.co.uk'."\r\n"; $ok=mail($emailto,$emailsubject,$emailmessage,$emailheader); mysql_close($connection); if ($ok) { header("Location: list.php"); /* Redirect browser */ exit; } else { $errmsg="There was a problem, please try later or telephone us direct."; $errsta="1"; include("edit_error.html"); //echo "<p>Mail could not be sent. Sorry!</p>"; exit; } ?> Thanks in advance what Im basically trying to do is just like a phpmyadmin function... you select rows you want to update with a checkbox and then it takes you to a page where the rows that are clicked are shown in forms so that you can view and edit info in them... and then have 1 submit button to update them all at once. Hey.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? As the title says I need help with multiple update system.. Can't really get it to work at all >.< Here's some code: $selectt = mysql_query("SELECT * FROM exercises WHERE user='" . $_SESSION["user"] . "' AND exname='" . $_GET["edit"] . "'"); echo '<form method="POST" action="exercises.php?edited">'; echo '<div id="newexx">'; while($raw = mysql_fetch_array($selectt)) { echo '<input type="text" name="up[' . $raw["id"] . ']" value="' . $raw["swe"] . '">'; echo '<input type="text" name="up1[' . $raw["id"] . ']" value="' . $raw["eng"] . '"><br>'; echo '<input type="hidden" name="id[' . $raw["id"] . ']">'; } echo '</div>'; echo '<input type="submit" value="Update Exercise">'; echo '</form>'; if(isset($_GET["edited"])) { $swe = $_POST["up"]; $eng = $_POST["up1"]; $id = $_POST["id"]; foreach($id as $value => $index) { $update = "UPDATE exercises SET swe='".$swe."', eng='".$eng."' WHERE id='".$index."'"; mysql_query($update); } Would be thankful for reply! I'm new to PHP and I was able to figure out how to populate data from my database into my text fields. I am trying to add the update information to the same php file; however, I am now receiving errors within the data I was able to populate,
Notice: Undefined variable: stmt in C:\xampp\htdocs\Cust_App\update.php on line 47 and errors with the Update statement
Notice: Undefined variable: stmtupdate in C:\xampp\htdocs\Cust_App\update.php on line 96 I had defined the customerID variable above in the code, but it isn't being captured from here. I tried setting up this query like the one which gathered the data, but I'm off by a little bit. I would like the option to be able to update all fields. Any help is appreciated. I'm trying to learn as I may get asked to update other forms in the future. (new boss asks a lot) <?php require_once('database.php'); ?> <!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"> <!-- the head section --> <head> <title>My Guitar Shop</title> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <!-- the body section --> <body> <div id="page"> <div id="header"> <h1>SportsPro Technical Support</h1> <p>Sports management software for the sports enthusiast.</p></h1> </div> <div id="main"> <h1>View/Update Customer</h1> <form action="update.php" method="get" > <?php if(isset($_GET['customerID'])) { $customerID = filter_input(INPUT_GET, 'customerID', FILTER_SANITIZE_NUMBER_INT); $sql = "SELECT * FROM customers WHERE customerID =$customerID "; $stmt = $db->query($sql); } ?> <div id="content"> <!-- display a table of products --> <h2>Customers</h2> <form method = "edit"> <?php foreach ($stmt as $cust) { ?> <div> <label>First Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['firstName']; ?>"> </div><br> <div> <label>Last Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['lastName']; ?>"> </div><br> <div> <label>Address</label> <input type="text" name="address" class ="form-control" value ="<?php echo $cust['address']; ?>"> </div><br> <div> <label>City</label> <input type="text" name="city" class ="form-control" value ="<?php echo $cust['city']; ?>"> </div><br> <div> <label>State</label> <input type="text" name="state" class ="form-control" value ="<?php echo $cust['state']; ?>"> </div><br> <div> <label>Country</label> <input type="text" name="countryCode" class ="form-control" value ="<?php echo $cust['countryCode']; ?>"> </div><br> <div> <label>Zip Code</label> <input type="text" name="postalCode" class ="form-control" value ="<?php echo $cust['postalCode']; ?>"> </div><br> <div> <label>Email </label> <input type="text" name="email" class ="form-control" value ="<?php echo $cust['email']; ?>"> </div><br> <div> <label>Phone Number </label> <input type="text" name="phone" class ="form-control" value ="<?php echo $cust['phone']; ?>"> </div><br> <div> <label>Password </label> <input type="text" name="password" class ="form-control" value ="<?php echo $cust['password']; ?>"> </div><br> <div> <?php } ?> <input type="Submit" name="Update_Data" value="Update Data"></input> <?php $sql2 = "UPDATE customers SET firstName = ". $stmtupdate['firstName']." WHERE customerID =$customerID "; $stmtupdate = $db->query($sql2); ?> </div> </div> <div id="footer"> <p> © <?php echo date("Y"); ?> SportsPro, Inc. </p> </div> </div><!-- end page --> </body> </html>
Good morning. I am looking fo some help with an update script to update all rows in a table. This is what I have for a form and all looks well. form.php <?php // run the query and put the results in an array variable called $result $result = mysql_query("SELECT * FROM table ORDER BY 'id', 'title', 'text', 'number'"); print "<form method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>ID</strong></td> <td align='center'><strong>Title</strong></td> <td align='center'><strong>text</strong></td> <td align='center'><strong>Number</strong></td> </tr>\n"; // start a loop to print all of the courses with their book information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['id']}</p></td>\n"; print "<td align='center'><input type='text' name='title' value='{$Update['title']}' /></td>"; print "<td align='center'><input type='text' size='40' name='text' value='{$Update['text']}' /></td>\n"; print "<td align='center'><input type='text' size='40' name='number' value='{$Update['number']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; print "</tr>\n"; ?><br /><br /> My question is. How do I update this info into the database with the proper info. ie. Update.php? I created this code to upload a member's main picture on his member page on website. I'll only include the query part of the code since that's what is relevant to my problem. The idea is basically to upload a new picture onto the database if no picture already exists for that member and display the picture on the page. If a picture already exists, then the script replaces the old picture with the new one upon upload. But for whatever reason I don't understand, when I try to replace the old pic, it gets inserted in a new row on the database instead of replacing the old row, and the new pic gets displayed on the web page alongside the old. Code: [Select] $query = "SELECT username FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"; $result = @mysql_query($query); $num = @mysql_num_rows($result); if ($num> 0) { //Update the image $update = mysql_query("UPDATE images SET image = '" . $image['name'] . "' WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"); $_SESSION['error'] = "File updated successfully."; //really should be session success message. header("Location: member.php"); exit; } else { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); $_SESSION['error'] = "File uploaded succussfully."; //really should be session success message. header("Location: member.php"); } So can anyone tell me what the problem is? Could the fact that my insert script actually uploads the image onto a folder on my server and only stores the path name in the database have anything to contribute to the mixup? Appreciate your responses in advance. Hi Guys, I want my UPDATE function from the code below to only update those fields that are NOT empty - if they are empty on submit then do not update or change any values from that field. I know that sounds odd, but with my file fields, when I submit to change something else at a later date it will overwrite the photo, download1,2 & 3 values and as a result I loose my files from the mysql table. Cheers, S <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo & Document Upload Upload $timestamp_photo = time(); $timestamp_download1 = time(); $timestamp_download2 = time(); $timestamp_download3 = time(); //This is the directory where the files will be saved //Photos $photo_target = "images/"; $photo_target = $photo_target .$timestamp_photo. basename( $_FILES['photo']['name']); //Documents $download_target = "documents/"; $download_target1 = $download_target .$timestamp_download1. basename( $_FILES['download1']['name']); $download_target2 = $download_target .$timestamp_download2. basename( $_FILES['download2']['name']); $download_target3 = $download_target .$timestamp_download3. basename( $_FILES['download3']['name']); //This gets all the other information from the form $photo = ($_FILES['photo']['name']); $download1 = ($_FILES['download1']['name']); $download2 = ($_FILES['download2']['name']); $download3 = ($_FILES['download3']['name']); //Pause Photo/Document Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '$timestamp_photo{$_FILES['photo']['name']}' , `download1` = '$timestamp_download1{$_FILES['download1']['name']}' , `download1name` = '{$_POST['download1name']}' , `download2` = '$timestamp_download2{$_FILES['download2']['name']}' , `download2name` = '{$_POST['download2name']}' , `download3` = '$timestamp_download3{$_FILES['download3']['name']}' , `download3name` = '{$_POST['download3name']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $photo_target)) { echo "<br />The file ".$timestamp_photo. basename( $_FILES['photo']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download1']['tmp_name'], $download_target1)) { echo "<br />The file ".$timestamp_download1. basename( $_FILES['download1']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download2']['tmp_name'], $download_target2)) { echo "<br />The file ".$timestamp_download2. basename( $_FILES['download2']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download3']['tmp_name'], $download_target3)) { echo "<br />The file ".$timestamp_download3. basename( $_FILES['download3']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload echo (mysql_affected_rows()) ? "<br />Edited Branch.<br />" : "<br />Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong>" round($courseMark) "<strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? |