PHP - Mysql Query Insert In While Loop
Hi,
Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks Similar TutorialsI am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> 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; } }```
I've got Code: [Select] for ($i=1; $i<=5; $i++) { if(isset($_POST['partsusedqty'.$i]) && $_POST['partsusedqty'.$i] != "" && $_POST['partsusedqty'.$i] != "0.00") { mysql_query("INSERT INTO partsused (ptnumber, partqty, partdesc, partprice) VALUES ($ticket, '$partsusedqty'.$i, '$partsuseddesc'.$i, '$partsusedprice'.$i)") or die(mysql_error()); } } I need to know the correct formatting to put these variable variables as values in the mysql query. With this particular code, I get the error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.1, ''.1, ''.1)' at line 2" I've tried formatting this an endless number of ways, but I used this particular example because its the one I really thought should work. Everything I've tried that doesn't throw an error put the $partsusedqty in the partqty, partdesc, and partprice fields. Thanks for any help! Hello every body,, i want to create a new database (auto generate duty assigned using form) in PHP and mysql..
i have four input fields:-
Name, Subject, Class & weekly lectures
now i want to insert name,subject & class into database, when i insert number of weekly lecture in field four..
insert automaticlly in database multiple time which i write in field four (weekly lecture)
database: table structure i have already is:::
id-name-subject-class-period-monday-tuesday-wednesday-thursday-friday-saturday
anybody please help me to create this database or just insert query ....
Hello Friends, Now i m stuck with simple insert query . here's the code Code: [Select] <?php include_once("conf.php"); $firstName=$_POST['fname']; $lastName=$_POST['lname']; $email=$_POST['email']; $dob=$_POST['dob']; $password=$_POST['pass']; $fname= stripslashes($firstName); $lname=stripslashes($lastName); $mail= mysql_real_escape_string($email); $password= mysql_real_escape_string($password); mysql_select_db('site'); $statement="Insert into Accounts(Name,lastName,emailId,DOB,password) VALUES($fname,$lname,$mail,$dob,$password)"; $query=mysql_real_escape_string($statement); mysql_query($query) or die("Cannot save data:</br> ".mysql_error()); echo "Data Saved Successfully"; ?> Now please explain me why i m getting the following error Cannot save data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@gmail.com,1988/12/20,password)' at line 1 Any help will be highly appreciated! I have tried many ways of storing an array of data that comes from a multiple selection form into a mysql table, including serialization. I am currently trying to do it by forming a string, and using the string in the insert query, but keep getting errors, or just nothing happening. I am not sure what I am doing wrong. Code: [Select] $categoryString = array(); if ($categoryArray){ foreach ($categoryArray as $category){ $categoryString[] = $category.'<br />';} } $categoryquery= "INSERT INTO categoryname VALUES('$categoryString')"; mysql_query($categoryquery); Thank you for your time as always. How can i use single quote for values? $qry='insert into tablename values('a','b');'; mysql_query("update pupils set record='running' where pid !='$testing[0]' I have created a registration page to access my website. After the user registrate himself should appear an alert saying that the registration was OK and a redirect to main.php page... however for some reason if I create an insert statement the alert and the redirect don't appear... If I remove the insert the alert and the redirect works... why? This is part of the code of my 3 files: registration.php (ajax call) $('#submit').click(function() {var username2 = $('#uname2').val(); var password2 = $('#psw2').val(); $.ajax({ url: 'ajax/response.php', type: 'GET', data: {username2 : username2, password2: password2}, success: function(data) { if(data === 'correct') { alert("Username and Password have been created!"); //don' work with the insert location.replace("main.php"); //don' work with the insert } else { alert("Username or password are not correct... please register yourself!"); } } }); }); response.php (answer to ajax call) if(isset($_GET['username2']) && isset($_GET['password2'])) {$username2 = $_GET['username2']; $password2 = $_GET['password2']; if (checkUser($pdo, $username2) === true) { echo 'duplicate'; } else { insertUserPwd($pdo, $username2, $password2); //including this line the redirect and the alert doesn't work... the insert is OK echo 'correct'; } } data_access.php (the function works but doesn't permit alert and redirect to appear) function insertUserPwd(PDO $pdo, $usr, $pwd){ $data = [ 'id' => '', 'user' => $usr, 'password' => $pwd ]; $sql = "INSERT INTO users (id, user, password) VALUES (:id, :user, :password)"; $stmt= $pdo->prepare($sql); $stmt->execute($data); } Can someone help me to fix the code? I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); Ok I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. Can anyone tell me why this is not INSERTing? My array data is coming out just fine.. I've tried everything I can think of and cannot get anything to insert.. Ahhhh! <?php $query = "SELECT RegionID, City FROM geo_cities WHERE RegionID='135'"; $results = mysqli_query($cxn, $query); $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { $insert_city_query = "INSERT INTO all_illinois SET state_id=$row[RegionID], city_name=$row[City] WHERE id = null" or mysqli_error(); $insert = mysqli_query($cxn, $insert_city_query); if (!$insert) { echo "INSERT is NOT working!"; exit(); } echo $row['City'] . "<br />"; echo "<pre>"; echo print_r($row); echo "</pre>"; } //while ($rows = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) else { echo "No results to get!"; } ?> Here is my all_illinois INSERT table structu CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Here is my source table geo_cities structu CREATE TABLE IF NOT EXISTS `1` ( `CityId` varchar(255) NOT NULL, `CountryID` varchar(255) NOT NULL, `RegionID` varchar(255) NOT NULL, `City` varchar(255) NOT NULL, `Latitude` varchar(255) NOT NULL, `Longitude` varchar(255) NOT NULL, `TimeZone` varchar(255) NOT NULL, `DmaId` varchar(255) NOT NULL, `Code` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; I have a code that will enter the information into a database but as follows: A B C D E 1 2 3 4 5 I am looking for it all to be on the same row like: A B C D E 1 2 3 4 5 Here is my code: <?php if($_SESSION['admin'] !='Yes') { Echo "You are not approved to view this page!"; } Else { echo "<form action=main.php?id=test1.php method=post>"; echo "<table border=0>"; $sql = "select * from `pipilots` WHERE `enabled` = 'Yes' ORDER BY `pilot name` ASC"; $result = mysql_query($sql) or die (mysql_error()); ?> <td>Date</td> <td><input name="pi" id="pi" type="hidden" size="10"> <a href="javascript:NewCal('pi','YYYYMMDD')"><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td> <?php echo "<tr><td>Pilot Name: </td><td><select name = pilotname>"; while ($row = mysql_fetch_array($result)) { echo "<option Value=".rawurlencode($row['pilot name']).">".$row['pilot name']."</option>"; } echo "</select></td></tr>"; $sql = "select * from `piprice` WHERE `enabled` = 'Yes' ORDER BY `product name` ASC"; $result = mysql_query($sql) or die (mysql_error()); $count = mysql_num_rows($result); while ($row = mysql_fetch_array($result)) { $pname[] = $row['product name']; echo "<tr><td>".$row['product name'].":</td><td> <input name=name[] type=text></td></tr>"; } echo"</table> <input name=submit type=submit Value=Add> </form>"; if(isset($_POST['submit'])) { $name = $_POST['name']; $date = $_POST['pi']; $pilotname = $_POST['pilotname']; echo rawurldecode($pilotname)."<br>"; echo $date."<br>"; for($i=0;$i<$count;$i++){ echo $pname[$i]." = ".$name[$i]."<br>"; $sql1="INSERT INTO `pi` (`pilot name`, `$pname[$i]`, `date`) VALUES ('$pilotname', '$name[$i]', '$date' )"; $result1=mysql_query($sql1) or die (mysql_error()); } }} ?> And this is the part that I think I need help with: if(isset($_POST['submit'])) { $name = $_POST['name']; $date = $_POST['pi']; $pilotname = $_POST['pilotname']; echo rawurldecode($pilotname)."<br>"; echo $date."<br>"; for($i=0;$i<$count;$i++){ echo $pname[$i]." = ".$name[$i]."<br>"; $sql1="INSERT INTO `pi` (`pilot name`, `$pname[$i]`, `date`) VALUES ('$pilotname', '$name[$i]', '$date' )"; $result1=mysql_query($sql1) or die (mysql_error()); } Any help would be great. Hi, I am trying to get this code to work: class People { public function insertAuthor(){ $authArray = $_POST['author']; $PCorder = 0; foreach($authArray as &$author): //Check if Pname exists $query = "SELECT * FROM People WHERE Pname = '".$author."'"; $result = mysql_query($query); if(mysql_num_rows($result) > 0): $row = mysql_fetch_array($result); $Pid = $row['Pid']; $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", ".$PCorder++.", now(), 0)"; //die($sql); $result = mysql_query($sql); endif; endforeach; } } so basically for EVERY author that is inserted, check to see if their name exists and do the INSERT. I don't get any errors with this code but it doesn't do the INSERT.. Any ideas why? Thanks again Regards Billy Here is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 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? My while loop to do the process to every member_id won't work.Its only printing one member_id thats done.Also my INSERT statement wont insert even that 1 member_id. Can someone please point my mistake. Code: [Select] <?php include 'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { if(!empty($array['lchild'])) $child[] = $array['lchild']; if(!empty($array['rchild'])) $child[] = $array['rchild']; if(!empty($array['lchild'])) $lchild = tree_gather($array['lchild']); if(!empty($array['rchild'])) $rchild = tree_gather($array['rchild']); if(!empty($lchild) && !empty($rchild)) { $merge_both = array_merge($lchild, $rchild); $child = array_merge($child, $merge_both); } elseif(!empty($lchild) && empty($rchild)) $child = array_merge($child, $lchild); elseif(!empty($rchild) && empty($lchild)) $child = array_merge($child, $rchild); } return $child; } $sql = mysql_query("SELECT member_id FROM member"); while($array = mysql_fetch_array($sql)) { $memid = $array['member_id']; $pair = tree_gather($memid) ; $remove = mysql_query("SELECT lchild,rchild FROM tree WHERE parent ='".$memid."'"); $remove_array = mysql_fetch_array($remove); if(!empty($remove_array['lchild']) || !empty($remove_array['rchild'])) { $count = count($pair); for($i = 0 ; $i < $count ; $i++) { if($pair[$i] != $remove_array['lchild'] && $pair[$i] !=$remove_array['rchild']) { $trimmed[] = $pair[$i]; } else { $two_one[] = $pair[$i]; } } } $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['lchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } if($done != 1) { $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['rchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } } $select_child = mysql_query("SELECT rchild,lchild FROM tree WHERE parent='".$memid."'"); $select_array = mysql_fetch_array($select_child); if(!empty($select_array['rchild'])) $rchild = tree_gather($select_array['rchild']); $rchild[] = $select_array['rchild']; if(!empty($select_array['lchild'])) $lchild = tree_gather($select_array['lchild']); $lchild[] = $select_array['lchild']; if(!empty($rchild)) { $right_count = count($rchild); } if(!empty($lchild)) { $left_count = count($lchild); } if($right_count < $left_count) { $pair_num = $right_count; } elseif($right_count == $left_count) { $pair_num = $right_count - 1; } else { $pair_num = $left_count; } if(count($two_one) == 3) { $dues_adjust = 100; if($pair_num >= 1) { $dues_adjust = $dues + 100; $calcom = 200 * $pair_num; $tds = 20.60 * $pair_num; $service = 9.40 * $pair_num; $paid = $calcom - $dues_adjust; $insert = mysql_query("INSERT INTO `payout` (member_id, binary, tds, service, total, dues, amount_paid, dues_adjust, pairs) VALUES ('".$memid."', '".$calcom."', '".$tds."', '".$service."', '".$calcom."', '0', '".$paid."', '".$dues_adjust."', '".$pair_num."')"); unset($pair); echo "<br />".$memid." Done"; } } } ?> Hi - I have spent 2 days trying to figure this out. I must be doing something stupid ... I am trying to update the DB with a collection of variables off of a various POST array's. I have indexed the variables so that I can loop through them with a FOR. However I am having all kinds of trouble: 1 - WEIGHT is giving 5 values even though the counter should only go 4 times. 2 - The WEIGHT variable is going into the wrong field in the DB even though I specify in my Query a specific place. 3 - I get undefined offset errors even though I have initialised the variables with their respective offsets. 4 - Adding the conditional statement adds even more offset errors even though they are initialised I am starting to wonder if my entire approach to updating my DB is flawed. As a student of PHP I think I need someone with more experience to look at what I am doing and tell me if something jumps out at them. There is a lot of statements echoing out values - and they all seem to check out. Man Many thanks for your advice Code: [Select] function finishedorder(){ $prodname = $_POST['prodname']; $prodid =$_POST['prodid']; $quantity = $_POST['quantity']; $pricelb = $_POST['pricelb']; $customerid = $_POST['customerid']; $price = $_POST['price']; $orderid = $_POST['orderid']; $weight = $_POST['weight']; echo "Varuable WEight"; print_r($weight); echo"<br/>"; echo "line 196 Weight"; print_r ($_POST['weight']); echo"<br/>"; echo "line 192 PriceLB"; print_r ($_POST['pricelb']); echo "<br/>"; echo "line 193 Price"; print_r ($_POST['price']); echo "<br/>"; echo "line 194 ProdID"; print_r ($_POST['prodid']); echo "<br/>"; echo "line 195 OrderID"; print_r ($_POST['orderid']); echo "<br/><br/>"; $numloops = count($_POST['prodid']); for ($i = 0; $i < $numloops ; $i++) { // !!! Start of the for loop !!! if (!isset($orderid[$i])) $orderid[$i] =''; if (!isset($prodid[$i])) $prodid[$i] =''; if (!isset($weight[$i])) $weight[$i] =''; if (!isset($pricelb[$i])) $pricelb[$i] =''; // This only initialises the Price & Weight variable to avoid an offset error message. if (!isset($weight[$i])) $weight[$i] =''; $ordervalue = $pricelb[$i] * $weight[$i]; echo " L. 216 The number is " . $i . "<br />"; echo "line 221 ProdID".$prodid[$i];echo "<br/>"; echo "line 217 Pricelb".$pricelb[$i];echo "<br/>"; echo 'Weight L. 219 weight[i]'. $weight[$i];echo "<br/>"; echo "line 220 weight".$weight; echo "<br/>"; echo "line 221 Numloops".$numloops; echo "<br/><br/>"; echo ' L. 225 $ordervalue ' .$ordervalue;echo "<br/>"; } //if ($pricelb[$i] == 0 ){ // conditonal statement // $ordervalue = $price[$i]; // } $sql =" UPDATE confirmedorder SET weight='$weight[$i]', ordervalue='$ordervalue', confirmedorder.picking = 'finished', confirmedorder.sale = 'open' WHERE prodID = '$prodid[$i]' AND OrderID = '$orderid[$i]' ; "; $this->db->query($sql); } // !! End For Loop. !! |