PHP - Help With Multi Insert Using For Loop
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? Similar Tutorialshello, is there a way to insert something 17 times into a database and change the 3rd field one at a time (from 1-17)? Code: [Select] $sql = "INSERT INTO picks VALUES ( NULL, '" . mysql_real_escape_string($userid) ."', '" . mysql_real_escape_string($weekid) ."', '" . mysql_real_escape_string($pickid) ."' )"; mysql_query($sql) or die('Error, Check you fields and try again.'); Hello, I have been at this for awhile now and cant seem to figure it out. I have 2 separate arrays like shown below and I am trying to insert each value into my database using one update query. I have tried a for loop inside each array, but only one column populates. I have tried breaking the values outside their for loop, etc, etc. Does anyone know a way this can be done? Code: [Select] //Cars $cars = array('ford', 'toyota', 'bmw'); //Places $places =arrray('Orlando','California','Texas'); foreach ($cars as $car){ foreach ($places as $place){ $place .=$place; } mysql_query("INSERT INTO vehicles (cars, places) VALUES ('" . $car. "', '" . $place . "'')"); } Hello I have this multi dimensional array which needs to be inserted to the database table.
[business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) [location_] => Array ( [text] => Array ( [0] => Lemara Main Office [1] => Themi branch [2] => Sinoni branch ) [priority] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) [photo_] => Array ( [path] => Array ( [0] => lemaraphoto.png [1] => themiphoto.png [2] => sinoniphoto.png ) ) [video_] => Array ( [path] => Array ( [0] => lemaravideo.mp4 [1] => themivideo.mp4 [2] => sinonivideo.mp4 ) ) [product_] => Array ( [p_id] => Array ( [0] => product photo [1] => product 3 photo [2] => Product 2 photo ) [text] => Array ( [0] => product desc [1] => product 3 desc [2] => product 2 desc ) [expire] => Array ( [0] => product expire [1] => product 3 expire [2] => Product 2 expire ) [title] => Array ( [0] => product [1] => Product 3 [2] => Product 2 ) ) [service_] => Array ( [p_id] => Array ( [0] => Service 2 photo [1] => service 3 photo [2] => service photo ) [text] => Array ( [0] => service 2 desc [1] => service 3 desc [2] => service desc ) [expire] => Array ( [0] => Service 2 expire [1] => service 3 expire [2] => service expire ) [title] => Array ( [0] => Service 2 [1] => service 3 [2] => service ) ) )That's the data. The database table, the table field and the corresponding value to be inserted in to the database. I'm using CodeIgniter any help would be appreciated. I have managed to make it wotk in this format [[business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) ]I used this code to do it function add_bz($data){ $this->db->trans_start(); $er=0; foreach($data as $table => $sql){ if($table==="business"){ $this->db->insert($table, $sql); $id = $this->db->insert_id(); } else { array_merge($sql, array('idd' => $id)); $this->db->insert($table, $sql);} } $this->db->trans_complete(); if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;} return TRUE; }Thanks in advance. could anyone please help me with the code which is i have already displayed data as a multi select list but now i need to select one or more from them and insert into another database table. would be appreciate your help. thanx 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); } Hi - good evening! thanks for the answer and all the help so far Oncemore the "Fetching-part" for a little parser-script: Here we go - new target urls: see the overview: http://dms-schule.bildung.hessen.de/index.html http://dms-schule.bildung.hessen.de/suchen/suche_schul_db.html Search by pressing the button "type" and then choose all schools with the mouse! Results 2400 schools: Here i can provide some "more help for getting the target!" - btw: see some details for this target-server: http://dms-schule.bildung.hessen.de/suchen/suche_schul_db.html?show_school=9009 http://dms-schule.bildung.hessen.de/suchen/suche_schul_db.html?show_school=9742 http://dms-schule.bildung.hessen.de/suchen/suche_schul_db.html?show_school=9871 well - you see i have to iterate over the sites - with a function /(a loop) http://dms-schule.bildung.hessen.de/suchen/suche_schul_db.html?show_school=1000 to 10000 BTW - after fetching the page i have to see which one are empty - those ones do not need to be parsed! Well - i want to do this with curl-multi since this is the most advanced way to do this: I see i have an array that can be filled I have to try it out...!! Well, I'm not pretty sure - but judging by the low level of PHP i have: I think that i may need a double array to define the URLs like: Can i do like so?: $urls = array( "siteone" => "suche_schul_db.html?show_school=%i", "sitetwo" => "suche_schul_db.html?show_school=%i", "sitethree" =>"suche_schul_db.html?show_school=%i" ); $params = array ( for ($i = 1; $i <= 10000; $i++) { // body of loop } // well i have to define the variables in a open form like abvove nand not below: // better than doing it like so: "siteone" => array(9009, 9742, 9871), ); then pass them to curl-multi as: foreach ($urls as $id => $url) { foreach ($params[$id] as => $param) { $i = $id . $param; $finalurl = sprintf($url, $param); $conn[$i] = curl_init($finalurl); I don't know if that's fits the needs tip that i am looking for but I hope so ;-) Can i do like so [see above]? What do yu think. i send you many greetings martin 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 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. 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"; } } } ?> 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! Dear All Members here is my table data.. (4 Columns/1row in mysql table)
id order_no order_date miles How to split(miles) single column into (state, miles) two columns and output like following 5 columns /4rows in mysql using php code.
(5 Columns in mysql table) id order_no order_date state miles 310 001 02-15-2020 MI 108.53 310 001 02-15-2020 Oh 194.57 310 001 02-15-2020 PA 182.22
310 001 02-15-2020 WA 238.57 ------------------my php code -----------
<?php
if(isset($_POST["add"]))
$miles = explode("\r\n", $_POST["miles"]);
$query = $dbh->prepare($sql);
$lastInsertId = $dbh->lastInsertId(); if($query->execute()) {
$sql = "update tis_invoice set flag='1' where order_no=:order_no"; $query->execute();
} ----------------- my form code ------------------
<?php -- Can any one help how to correct my code..present nothing inserted on table
Thank You Edited February 8, 2020 by karthicbabuHi, 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 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. !! I have developed the following code, which queries a MySQL database and returns multiple results using several WHILE loops: Code: [Select] <?php # if submit_hash is present, then pull up the attendance from specified hash if($_GET['submit_hash']) { # select all the hashers from the specified hash $query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = " . $_GET['hash_id'] . " && hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id ORDER BY ha.hasher_name "; $result = mysql_query($query) or die('Error selecting Hash attendance.'); $x = 1; while($row = mysql_fetch_array($result)) { if($x == 1) { echo '<strong>' . $row['hash_num'] . ' ' . $row['hash_name'] . ' - ' . date("D, d M Y", strtotime($row['hash_date'])) . '</strong><em>Total Hashers: ' . mysql_num_rows($result) . '</em>'; $x++; } # see if this person was the hare if($row['hare_id'] == $row['hasher_id'] || $row['hare2_id'] == $row['hasher_id'] || $row['hare3_id'] == $row['hasher_id']) { $hare = '- hare'; } else { $hare = ''; } echo $row['hasher_name'] . ' <b>' . $hare . '</b>'; } } else if($_GET['submit_hasher']) { # if submit_hasher is present, pull up all of their hashes and aliases # select all the hashes that this person has attended $a_query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id && hr.hasher_id = " . $_GET['hasher_id'] . " ORDER BY h.hash_date DESC "; $a_result = mysql_query($a_query) or die('Error selecting the person\'s Hashes . '); $x = 1; while($a_row = mysql_fetch_array($a_result)) { if($x == 1) { echo '<strong>Hash Attendance Record For ' . $a_row['hasher_name'] . '</strong> <em>(' . mysql_num_rows($a_result) . ' total hashes)</em>'; $x++; } echo '#' . $a_row['hash_num'].' ' . $a_row['hash_name'] . ' on ' . date("D, d M Y", strtotime($a_row['hash_date'])); # see if this person was a hare if($a_row['hasher_id'] == $a_row['hare_id'] || $a_row['hasher_id'] == $a_row['hare2_id'] || $a_row['hasher_id'] == $a_row['hare3_id']) { echo ' - <b>hare</b>'; } echo ''; } echo ''; } echo ' <table width="100%"> <br /> <tbody> <tr> <br /> <td> '; ?> The problem is that everything that is returned from the WHILE loops is displayed in a single line. However, I want the data displayed with a line break between each result, like this: Header Return 1 from WHILE loop Return 2 from WHILE loop Return 3 from WHLIE loop How do I need to modify the code to make it display appropriately? I 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. <?php function test(){ $x = ''; $arr = array('co'=>'color','ct'=>'design','cv'=>'weight','cm'=>'hight','cp'=>'price'); foreach($arr as $k=> $v){ $x .= '<tr><td> Td '.$k.' </td><td> Td '.$v.'</td></tr>' /* AFTER ACCESS THE ROW THAT DISPLAY "<tr><td> Td ct </td><td>Td design </td></tr>" */ /* insert HTML CODE (not by echo ) then complete the loop */ } return $x; } ?>
good day dear community, i am workin on a Curl loop to fetch multiple pages: i have some examples - and a question: Example: If we want to get information from 3 sites with CURL we can do it like so: $list[1] = "http://www.example1.com"; $list[2] = "ftp://example.com"; $list[3] = "http://www.example2.com"; After creating the list of links we should initialize the cURL multi handle and adding the cURL handles. $curlHandle = curl_multi_init(); for ($i = 1;$i <= 3; $i++) $curl[$i] = addHandle($curlHandle,$list[$i]); Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle. ExecHandle($curlHandle); for ($i = 1;$i <= 3; $i++) { $text[$i] = curl_multi_getcontent ($curl[$i]); echo $text[$i]; } In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle! If we want to another Fetch of sites with cURL-Multi - since this is the most pretty way to do it! Well I am not sure bout the string concatenation. How to do it - Note I want to fetch several hundred pages: see the some details for this target-server sites - /(I have to create a loop over several hundred sites). * siteone.example/?show_subsite=9009 * siteone.example/?show_subsite=9742 * siteone.example/?show_subsite=9871 .... and so on and so forth Question: How to appy this loop into the array of the curl-multi? <?php /************************************\ * Multi interface in PHP with curl * * Requires PHP 5.0, Apache 2.0 and * * Curl * ************************************* * Writen By Cyborg 19671897 * * Bugfixed by Jeremy Ellman * \***********************************/ $urls = array( "siteone", "sitetwo", "sitethree" ); $mh = curl_multi_init(); foreach ($urls as $i => $url) { $conn[$i]=curl_init($url); curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);//return data as string curl_setopt($conn[$i],CURLOPT_FOLLOWLOCATION,1);//follow redirects curl_setopt($conn[$i],CURLOPT_MAXREDIRS,2);//maximum redirects curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,10);//timeout curl_multi_add_handle ($mh,$conn[$i]); } do { $n=curl_multi_exec($mh,$active); } while ($active); foreach ($urls as $i => $url) { $res[$i]=curl_multi_getcontent($conn[$i]); curl_multi_remove_handle($mh,$conn[$i]); curl_close($conn[$i]); } curl_multi_close($mh); print_r($res); ?> I look forward to your ideas. 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; } }```
First page adds a new job number, then the order page loaded with the job number id as a get id. Basically there is a while loop in the order page which shows products/services client can order and he chooses what he requires 'one or eight services' (8 in total) and some other variables like date of order and client name etc. Here is the order item code The first sql statement executes fine, but in the second sql query nothing happens $sql="insert into job_order(order_num,order_date,order_customer_id, order_remarks) values(".$_GET['id'].",NOW(),".$_POST['companyBox'].",'".$_POST['remarkBox']."');"; $res=mysql_query($sql); $id=mysql_insert_id(); foreach($_POST as $key => $value) { if(!empty($value)) { $key.' => '.trim(strip_tags($value)); $order="INSERT INTO orderprod (order_num,prod_id,order_amount,teeth_amount) VALUES ('$_GET[id]','$value','$value','$value');"; $orderres=mysql_query($order) or die(mysql_error()); } }?>$sql="insert into job_order(order_num,order_date,order_customer_id, order_remarks) values(".$_GET['id'].",NOW(),".$_POST['companyBox'].",'".$_POST['remarkBox']."');"; $res=mysql_query($sql); $id=mysql_insert_id(); foreach($_POST as $key => $value) { if(!empty($value)) { $key.' => '.trim(strip_tags($value)); $order="INSERT INTO orderprod (order_num,prod_id,order_amount,teeth_amount) VALUES ('$_GET[id]','$value','$value','$value');"; $orderres=mysql_query($order) or die(mysql_error()); } } ?> ============= This is the formI have removed parts which are irrelevant. Please note that dateBox and companyBox are not required to be looping as they are only for first table, echo "<form action=".$config_basedir."./vieworder.php?id=".$_GET['id']." name=form1 method=post>";?><table><tr><td><h4>JOB ORDER</H4></TD><TD></TD></TR><TR><TD>ORDER NUMBER</TD><TD><?PHP ECHO $_GET['id'] ?></td></tr><tr><td>ORDER DATE</td><td><input type=text name=dateBox></td></tr> <tr><td>COMPANY NAME</td><td><?PHP$sql="select * from customers";$res=mysql_query($sql);echo "<select name=companyBox><option value=''>Please select</option>";WHILE($fetch=mysql_fetch_assoc($res)){ echo "<option value='".$fetch['id']."'>".$fetch['cust_name']."</option>";} echo "</select>"; echo "</td></tr>"; ?> </table> <table><tr><th>ITEM</th><th>QUANTITY</th><th>N0. of Teeths</th></tr><tr><?PHP$sql="select * from products";$res=mysql_query($sql); WHILE($fetch=mysql_fetch_assoc($res)){ echo "<td><input type=text name=desBox value='".$fetch['prod_id']."'>".$fetch['prod_name']."</td><td><input type=text name=quantBox></td><td><input type=text name=teethBox></td>";echo "</tr>";}echo "</table>";?>echo "<form action=".$config_basedir."./vieworder.php?id=".$_GET['id']." name=form1 method=post>"; ?> <table> <tr> <td><h4>JOB ORDER</H4></TD><TD></TD> </TR> <TR> <TD>ORDER NUMBER</TD><TD><?PHP ECHO $_GET['id'] ?></td> </tr> <tr> <td>ORDER DATE</td><td><input type=text name=dateBox></td> </tr> <tr> <td>COMPANY NAME</td><td> <?PHP $sql="select * from customers"; $res=mysql_query($sql); echo "<select name=companyBox><option value=''>Please select</option>"; WHILE($fetch=mysql_fetch_assoc($res)){ echo "<option value='".$fetch['id']."'>".$fetch['cust_name']."</option>";} echo "</select>"; echo "</td></tr>"; ?> </table> <table> <tr> <th>ITEM</th><th>QUANTITY</th><th>N0. of Teeths</th> </tr> <tr> <?PHP $sql="select * from products"; $res=mysql_query($sql); WHILE($fetch=mysql_fetch_assoc($res)){ echo "<td><input type=text name=desBox value='".$fetch['prod_id']."'>".$fetch['prod_name']."</td> <td><input type=text name=quantBox></td> <td><input type=text name=teethBox></td>"; echo "</tr>";} echo "</table>"; ?> HERE IS THE IMAGE showing the populated services. http://dubads.com/images/order.jpg |