PHP - Update Foreach Loop Multi Records
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); } Similar TutorialsIam trying to access amazon API and iam receiving XML perfectly but now I dont know how to traverse all records as in the below example Iam having 3 records but can't travers the xml using foreach Loop Please help me out and tell me how to use foreach loop ?? Its urgent $search="9781439181799,9780393334296,9781605298627"; $result = $obj->getItemByUpc($search, "Books"); foreach($result->children() as $key ) { $data = $key->Items->Request->ItemLookupRequest->ItemId."<br/ >"; echo $data; } Moderator Edit: added [php] tags Hi Guys, How come i am unable to delete a record with the same id from multi records with the following php code? $rid = "SELECT month_ID FROM monthA WHERE userID = '".$_POST['userID']."' AND thisMonth = '".$_POST['month']."' AND thisYear = '".$_POST['year']."'"; $rid_month = mysql_query($rid); $row = mysql_fetch_array($rid_month); $month_ID = $row["month_ID"]; $rid = "SELECT * FROM monthB WHERE month_ID = '$month_ID'"; $rid_month = mysql_query($rid); $row = mysql_fetch_array($add_member); while ($row = mysql_fetch_array($rid_month)) { $month_ID = $row["month_ID"]; $rid = "DELETE FROM monthBB WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); } $rid = "SELECT * FROM monthC WHERE month_ID = '$month_ID' "; $rid_month = mysql_query($rid); while ($row = mysql_fetch_array($rid_month)) { $month_ID = $row["month_ID"]; $rid = "DELETE FROM monthCC WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); } $rid = "DELETE FROM monthA WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); I have tried a number of ways without any luck. How ever if i use this code? mysql_query("DELETE FROM monthA WHERE month_ID = '$month_ID'"); It allows me to delete one row from one table only. Please advise hi there. i have a class that queries my db, creates an array objects representing a collection of the items returned. when i pass the array back to the caller and then try to loop through the array, it keeps displaying the same record - i think it's the last record that is displayed however, when i try the same code in the class, it prints out each unique record. i tried doing a reset(myarray); on the caller but that dind't work either. any suggestions? here's the code to loop through the array: if ( count( $myarray ) > 0 ) { //reset($lineItem_array); foreach ( $myarray as $lineitem ) { echo($lineitem->getName()."~"); echo($lineItem->getOId()."~"); echo($lineItem->getProduct()."~"); echo($lineItem->getPIP()."~"); echo($lineItem->getQuantity()."~"); } } } } 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? I want to create an array from a file with this structure TITLE1, HEADER1, key11, key12, key13, key14 TITLE2, HEADER2, key21, key22, key23, key24 . . . How I can get a foreach with these elements: $title="TITLE" $header="HEADER" $key="(one random key)" If needed, I can change the file structure too. I am really not sure if this is a problem with me (probably is), php or mysql. I have a calendar that I am adding events to. If I want to edit only the date I can but only once after I make this update I am out. If I attempt to update the time or event title the database is never updated and I am no longer able to update the date. here is the controller for the save. Code: [Select] <?php function eventsave() { $details = $_POST; $this->load->model('eventsmodel'); $this->eventsmodel->eventsave($details,'', TRUE); redirect('/admin/events', 'location'); } ?> I have turned off the redirect to see if I was getting any errors and they seem to be non existent. Here is the model that is used to create a new entry and update a record. Code: [Select] <?php function eventsave($event) { $startdate = explode('-', $event['startdate']); $start = mktime($event['starthour'], $event['startmin'], 0, $startdate['0'], $startdate['1'], $startdate['2']); $end = mktime($event['endhour'], $event['endmin'], 0, $startdate['0'], $startdate['1'], $startdate['2']); $name = $event['name']; if (isset($event['id'])) { // if is true then this is an update not a new event $data = array( 'name' => $name, 'start' => $start, 'end' => $end ); $this->db->where('id', $id); $this->db->update('events', $data); }else{ $this->db->set('name', $name); $this->db->set('start', $start); $this->db->set('end', $end); $this->db->insert('events'); } } ?> I am using code igniter if that helps and the information being submitted by the form looks good. This is the submitted update array and the new event array is just missing the "id" Code: [Select] Array ( [name] => test [startdate] => 05-14-2011 [starthour] => 1 [startmin] => 0 [endhour] => 1 [endmin] => 0 [id] => 54 [saveevent] => save ) Any suggestions would be appreciated. Thank you. Hi all, I'm trying to make a query that allows the user to edit the name of a entry in SQL. I believe I have the corect Syntax but I'm not sure if I have the code set up correctly. I am using 2 queries when I think it is possible with one. The first query is used to Pint out results for a certain year and the second to update the names. Code: [Select] $desiredYear = $_POST['year']; $nameEdit = $_POST['edit']; $origName = $_POST['orig']; echo ' The year you have chosen is '.$desiredYear; $describeQuery = "SELECT ID, Name, (SELECT SUM(SalesVolume) as SalesVolume FROM MonthlySales WHERE ProductCode=Products.ID AND Year = '$desiredYear') AS num_sales FROM Products"; $editQuery = "UPDATE Products SET Name = '$nameEdit' WHERE Name ='$origName'"; $results = sqlsrv_query($conn, $describeQuery); echo '<table border="1" BORDERCOLOR=Black>'; echo '<tr><th bgcolor = "LightBlue">Name</th><th bgcolor = "LightBlue" >ID</th> <th bgcolor = "LightBlue" >Sales</th></tr>'; while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) { echo '<tr>'; echo '<td >' .$row['Name'].'</td>'; echo '<td>' .$row['ID'].'</td>'; echo '<td>' .$row['num_sales'].'</td>'; echo '</tr>'; } echo '</table>'; sqlsrv_close($conn); Can somebody help me with this? Thank you Hi guys, I am trying to UPDATE some records on a mySQL database but can't seem to find out why it is not working. This is my code. Code: [Select] <?php $latitude = $_POST['lat_location']; $longitude = $_POST['long_location']; $unique_ID = $_POST['unique_ID']; include('connect2.php'); $query = mysql_query("SELECT * FROM user_location WHERE unit = '$unique_ID'"); $numrows = mysql_num_rows($query); if ($numrows == 1) { $query2="UPDATE user_location SET lat = '$latitude', long = '$longitude' WHERE unit = '$unique_ID'"; mysql_query($query2); $test = "matches"; } else { mysql_query("INSERT INTO user_location VALUES ('','$unique_ID','$latitude','$longitude')"); $test = "not match"; } echo $test . "<br />"; echo $numrows; ?> The script receives the data via the POST method and assigns it to variables. Then I query the database for one of those variables and check how many results are found. If 0 results are found then a new record is created on the database, but if there is 1 record found then the record that is found has to be UPDATED. When the result is 0 the scripts creates the new record fine, but if the result is 1 it doesn't update. I just can't figure out why. Any help will be greatly appreciated. Thanks in advanced, Hi there, Im fairly new at php and mysql but nevertheless im trying to build a web based campaign game for starwars minatures boardgame. Its fairly straightforward and going well.. However ive been thinking about how it will work and have stumbled across a possible problem (because of my limited craft at programming). I want to have a single form that updates all records in the tables, this would simulate an "end of turn" button. Im sure i can do this if doing stuff in the game (e.g. move, create , modify, delete, fleets/ships and auto increment ships hulls simulating repair) if it was done on the same page. However i wanted to to initiate some of these adjustments in their respective pages (fleet.php, planets.php, ships.php etc) and then once the user is happy to click the end turn button somewhere which would update all of these things at the same time.. Is this possible at all??? If anybody could help that would be brilliant. Thank you p.s. if anybody wants a copy of the finished product when its complete, your most welcome. I have a problem . I 've been trying for a long time to make an update for php mysql to change the data. but every time I do not manage to make it work with a form. but it works if I only if I put this ($ sql = "UPDATE users SET username = 'value' WHERE id = 10 " ; ) so it only works when I put the value of the id. but I want in an html form to indicate what I want to change and what id goes. but I have tried so long that I do not feel like I so want someone help me. make the same database and same as my records and make the code and test it if it works show me please my database name : web test my table called : users my records are called : id int ( 11) AUTO_INNCREMENT username , varchar ( 255 ) password , varchar ( 255 ) first_name , varchar ( 255 ) last_name , varchar ( 255 ) email, varchar ( 255 ) Age, int ( 11) Look, my update.php is like this now <?php $servername = "localhost"; $username = "root"; $password = "....."; $dbname = "webtest"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "UPDATE users SET password='cotton candy' WHERE id=10"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?> but now i have still have to go into the php file to change the valeu or the id but i looked on site and youtube how to put it in a simple html form but it still does not work. i want it in a html from. I want that when I enter the ID that the data of the user appears and that I can change any valeu separately. Hi, I was thinking of creating a table for this current code and place only 3 options in a row, however I do not know how to execute a command which will allow me to do so, I have attached 2 pictures to describe what I will like to achieve. Below is my code as well. Any advice? Thanks $query = ("SELECT * FROM tutor_preferred_district ORDER BY district_id ASC"); $sql = mysqli_query($dbc, $query) or die(mysql_error()); while($data = mysqli_fetch_array($sql)) { echo'<table>'; echo '<input name="district" type="checkbox" id="'.$data['district_id'].'" value="'.$data['district_id'].'">'; echo '<label for="'.$data['district_id'].'">'.$data['district_name'].'</label>'; echo'<table>'; } Hi is it possible to update multiple records of the same table using a single hidden field with a while loop??? For example: Code: [Select] <?php if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE ships SET HealthA=%s WHERE ShipID=%s", GetSQLValueString($_POST['healtha'], "int"), GetSQLValueString($_POST['shipid'], "text")); ?> <input name="healtha" type="hidden" id="healtha" value="<?php echo $row_Ships['HealthA'] + 1; ?>" /> <input name="shipid" type="hidden" id="shipid" value="<?php while($row = mysql_fetch_assoc($Ships)){ echo $row_Ships['ShipID']; }?>" /> If its not possible what else could i do to achieve this please? Thank you Hi ive been stuck for a while now and i just cant get my head around it so if you could help i'd be well chuffed. I'm trying to update multple rows in a table depending upon the results of another. I have a form that enables me to update a table called fleet. Another table called ships is realted to the fleet table as each ship is in a fleet: fleet ----- Fleetname* Location Detected ships ------ ShipID* Fleetname * Shipname The particular fleet i am editing is parsed as a url parameter. I made a query to search for all the ships that are in the fleet i am editing: Code: [Select] $colname_ShipsInfleet = "-1"; if (isset($_GET['recordID'])) { $colname_ShipsInfleet = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_ShipsInfleet = sprintf("SELECT * FROM ships WHERE FleetName = %s", GetSQLValueString($colname_ShipsInfleet, "text")); $ShipsInfleet = mysql_query($query_ShipsInfleet, $swb) or die(mysql_error()); $row_ShipsInfleet = mysql_fetch_assoc($ShipsInfleet); $totalRows_ShipsInfleet = mysql_num_rows($ShipsInfleet); It searched the ships WHERE the FleetName (which is the primary key of the fleet table) is parsed as a url parameter. The appropriate ship records that are generated i want to use so a field can be updated. For example im updating a fleet record and and setting the location (Planet Name) to a different value. I want the Ship records that are of that particular fleet to update a field (PlanetName) in ship table when the fleet table is updated. Code: [Select] if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE ships WHERE ShipID = $row_ShipsInfleet['ShipID'] SET PlanetName=%s", GetSQLValueString($_POST['select'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); $updateSQL = sprintf("UPDATE fleet SET PlanetName=%s, Detected=%s, Faction=%s WHERE FleetName=%s", GetSQLValueString($_POST['select'], "text"), GetSQLValueString(isset($_POST['checkbox']) ? "true" : "", "defined","1","0"), GetSQLValueString($_POST['hiddenField2'], "int"), GetSQLValueString($_POST['hiddenField'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); I'm really not sure how to proceed here so please if you can help me out that would be ace. Thank You Hello everebody, i have code to updare many rows at once using "for". when i click submit button nothing happens, where is the error in my code? thank you very much for your help <?php $hoster="db.mkq.de"; $username="dbxxxxxx"; $password="xxxxxx"; $db_name="xxxxxx"; mysql_connect("$hoster", "$username", "$password") or die("cannot connect"); mysql_select_db("$db_name") or die("cannot select DB"); $sql="SELECT * FROM gbook"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <table width="500" border="0" cellspacing="1" cellpadding="0"> <form name="form1" method="post" action=""> <tr> <td> <table width="500" border="0" cellspacing="1" cellpadding="0"> <tr> <td align="center"><strong>Id</strong></td> <td align="center"><strong>www</strong></td> <td align="center"><strong>email</strong></td> <td align="center"><strong>pwd</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"> <input name="id[]" type="text" id="id" value="<? echo $rows['id']; ?>"> </td> <td align="center"> <input name="www[]" type="text" id="www" value="<? echo $rows['www']; ?>"> </td> <td align="center"> <input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"> </td> <td align="center"> <input name="pwd[]" type="text" id="pwd" value="<? echo $rows['pwd']; ?>"> </td> </tr> <?php } ?> <tr> <td colspan="4" align="center"><input type="submit" name="submit" id="submit" value="update"></td> </tr> </table> </td> </tr> </form> </table> <?php if($submit) { for($i=0;$i<$count;$i++) { $sql1="UPDATE gbook SET www='$www[$i]', email='$email[$i]', pwd='$pwd[$i]' WHERE id='$id[$i]'"; $result1=mysql_query($sql1); } } if($result1) { header("location:editmulti3.php"); } mysql_close(); ?> Have a web page that displays a number of update forms depending on the amout of records that get returned from a mysql query, if query returns 4 records then the page will display 4 identical forms, the trouble i'm having is getting the each of the 4 forms to display a different record as at the moment they all show just first record of query. I have played around with loops but not getting anywhere which may be due to my limited knowledge code for page is below Code: [Select] <?php $numberofrow =mysql_num_rows($Recordset1); for($counter = 1;$counter<=$numberofrow;$counter++){ ?> <label for="hometeam2"></label> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <label for="hometeam"></label> <input name="fixid" type="text" id="fixid" value="<?php echo $row_Recordset1['FixtureID']; ?>" /> <input name="hometeam" type="text" id="hometeam2" value="<?php echo $row_Recordset1['hometeamname']; ?>" /> <label for="homescore"></label> <input name="homescore" type="text" id="homescore" value="<?php echo $row_Recordset1['homescore']; ?>" /> <label for="awayscore"></label> <label for="fixid"></label> <input name="awayscore" type="text" id="awayscore" value="<?php echo $row_Recordset1['awayscore']; ?>" /> <label for="awayteam"></label> <input name="awayteam" type="text" id="awayteam" value="<?php echo $row_Recordset1['awayteamname']; ?>" /> <input type="submit" name="update" id="update" value="Submit" /> <input type="hidden" name="MM_update" value="form1" /> i have a form per row with an update button my problem is to update each row at a time so i created a unique update button per row, not working Code: [Select] <table cellspacing="0" cellpadding="0" border="1"> <col width="75" span="5" /> <tr> <td width="75">Proposal</td> <td width="75"> </td> <td width="75">Supplier</td> <td width="75">Downpayment</td> <td width="75">Payment Method</td> <td width="75">Status</td> <td width="75"> </td> </tr> <?php do { ?> <tr><form id="form1" name="form1" method="post" action=""> <td><?php echo $row_RsDownPayment['RequestID']; ?>-<?php echo $row_RsDownPayment['ProposalID']; ?></td> <td><?php echo $row_RsDownPayment['CustomerLastName']; ?></td> <td><?php echo $row_RsSupplier['SupplierName']; ?></td> <td><?php echo $row_RsDownPayment['PREPAYMENT2SUPPLIER']; ?></td> <td><select name="PaymentMethod" id="PaymentMethod"> <option value="0">Choose</option> <option value="Bank Transfer">Bank Transfer</option> <option value="CreditCard">CreditCard</option> <option value="Cash">Cash</option> <option value="PayPal">PayPal</option> </select></td> <td><?php echo $row_RsStatus['StatusLabel']; ?></td> <td><input name="<?php echo $U='Update'.$row_RsDownPayment['ProposalID'];?>" type="submit" value="Update" /> </td></form> </tr> <?php $con = mysql_connect("host","db","db"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_query("SET NAMES 'utf8'"); mysql_select_db("db", $con); if (isset($_POST['Update121'])) { $query=mysql_query("UPDATE proposals SET StatusID='$_POST[StatusID]' WHERE ProposalID = '$row_RsDownPayment[ProposalID]'"); exit; } ?> <?php } while ($row_RsDownPayment = mysql_fetch_assoc($RsDownPayment)); ?> </table> Hi all, I have a data base with the following table: ---member_data--- id ^ mid ^fieldname^ fieldvalue 1 - 2 - applicant - Seth Smith 2 - 4 - firstname - Chris 3 - 4 - lastname - Cooper 4 - 7 - full_name - Joey Jones 5 - 7 - occupation - Programmer 6 - 7 - phone - 800-555-1212 And below is a snippet that I use to display the selected members data for editing ------------------------------- <table> <tr> <td>Name:</td> <td>Value:</td> </tr> <?php $query = "SELECT * FROM member_data WHERE mid='$mid'"; $result= mysql_query($query); while($row = mysql_fetch_array($result)) { $fieldname = $row["fieldname"]; $fieldvalue = $row["fieldvalue"]; ?> <tr> <td><input type="text" name="<?php echo $fieldname;?>" value="<?php echo $fieldname;?>"></td> <td><input type="text" name="<?php echo $fieldvalue;?>" value="<?php echo $fieldvalue;?>"></td> <?php } ?> </tr> </table> ------------------------------- My question is: - using the Db example above: - lets say Ive selected mid#7 (member id 7) to edit which is displayed using the snippet code from above. - once displayed how do I edit mid#7 given the fact that mid#7 is located on 3 seperate rows from the same table? Thank you, Dave *ALSO - I tried the snippet below which did Not work. foreach($_POST as $key => $val) { $sql = "UPDATE member_data SET fieldname='$key', fieldvalue='$val' WHERE mid='$mid'"; $result = mysql_query($sql); } can anybody tell me what's wrong with my query ? $filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel, vpre FROM pf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; I am using this in while loop with ps_pagination class but getting 2 records for same set of files. in other words its running while loop 2 time complete code is here... $filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel FROM ibwf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; $pager = new PS_Pagination($conn, $filesa, 9, 5, $albumid, $sortid, $sub, $selectalbum3[uid], $title, $collective); $results = $pager->paginate(); while($files=mysql_fetch_array($results)) { // Blah Blah } Output is something like this 1. song 1 2. song 2 3. song 3 4. song 4 1. song 1 2. song 2 3. song 3 4. song 4 Thanks is advance hi all i have a problem here, Iv got a form that uploads images to a folder and updates the db with the name of that image, that work ok but if one of the upload field are left blank then the script updates the db with empty values how can i get it to only update the db with only submitted form field data???? here is the form Code: [Select] <?php if (isset($_GET['id'])) { $id = $_GET['id']; } ?> <form action="ud_image.php?id=<? echo "$id"?>" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table class="udp"> <tr> <th>Thumbnail:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 1:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 2:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 3:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 4:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /><input type="submit" name="Submit" value="Upload" /></td> </tr> </table> </form> and here is the processing page <?php include("protect/password_protect.php"); error_reporting(E_ALL); include ("../includes/db_config.php"); $con = mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $path1= "../thumbnails/".$_FILES['ufile']['name'][0]; $path2= "../images/".$_FILES['ufile']['name'][1]; $path3= "../images/".$_FILES['ufile']['name'][2]; $path4= "../images/".$_FILES['ufile']['name'][3]; $path5= "../images/".$_FILES['ufile']['name'][4]; //copy file to where you want to store file copy($_FILES['ufile']['tmp_name'][0], $path1); copy($_FILES['ufile']['tmp_name'][1], $path2); copy($_FILES['ufile']['tmp_name'][2], $path3); copy($_FILES['ufile']['tmp_name'][3], $path4); copy($_FILES['ufile']['tmp_name'][4], $path5); ?> <html> <head> <title>Update Project Images</title> <link rel="stylesheet" type="text/css" href="../../project/backend/style.css" /> </head> <body> <table class="udip"> <tr> <th><? echo "<img src=\"$path1\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path2\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path3\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path4\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path5\" width=\"150\" height=\"150\">";?></th> </tr> <tr> <td><? echo "File Name :".$_FILES['ufile']['name'][0]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][1]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][2]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][3]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][4]."<BR/>";?></td> </tr> <tr> <td><?echo "File Size :".$_FILES['ufile']['size'][0]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][1]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][2]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][3]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][4]."<BR/>";?></td> </tr> <tr> <td><? echo "File Type :".$_FILES['ufile']['type'][0]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][1]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][2]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][3]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][4]."<BR/>";?></td> </tr> </table> </body> </html> <? $filesize1=$_FILES['ufile']['size'][0]; $filesize2=$_FILES['ufile']['size'][1]; $filesize3=$_FILES['ufile']['size'][2]; $filesize4=$_FILES['ufile']['size'][3]; $filesize5=$_FILES['ufile']['size'][4]; if($filesize1 && $filesize2 && $filesize3 && $filesize4 && $filesize5 != 0) { echo "We have recieved your files<p>"; } else { echo "Error in you images check and try again Database has been updated to blank images so no images will be shown on details page."; } $query = "UPDATE $db_table SET thumbnail = '".$_FILES['ufile']['name'][0]."', image1 = '".$_FILES['ufile']['name'][1]."', image2 = '".$_FILES['ufile']['name'][2]."', image3 = '".$_FILES['ufile']['name'][3]."', image4 = '".$_FILES['ufile']['name'][4]."' WHERE id = '".$_GET['id']."'"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> im trying to do a multi insert form using for loop. the concept is specifying a number and then using it in the for loop. the loop then makes a number of fields depending on the specified number. after that i use another for loop to insert the grouped fields together. code for specifying desired number Code: [Select] <? if ($_GET[num]=="") { ?><form name="form1" method="post" action="multiup.php?num=1"> <input name="num" type="text" value="10" maxlength="2"> <input type="submit" name="button" id="button" value="Submit"> </form><? } ?> Code: [Select] <? } else { ?><form name="form2" method="post" action="multiup2.php"> <input name="adder" type="hidden" value=""> <input name="num" type="hidden" value="<? echo $_POST[num]; ?>"> code for displaying fields <? for ($i=1;$i<=$_POST[num];$i++) { echo "groupnumber<br /> <input name='eno$i' type='text' value='$i'> Thumb <input name='thumb$i' type='text'> link1<br /> ";} ?> the insert code Code: [Select] <? if(isset($_POST['submit']) && ($_POST['submit'] == "Submit")) { $con = mysql_connect("lalalalala"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("kiphi_main", $con); for ($i=1;$i<=$_POST[num];$i++) { $title="$eno$i"; $sql="INSERT INTO articles (title) VALUES ('$_POST[$title]')"; } } if (!mysql_query($sql,$con)) {echo testest;}?> problem is i cant get it to work... should i try a different approach? |