PHP - Help Optimizing Loop
Code: [Select]
<?php $query = 'SELECT COUNT(*) FROM `fonts`'; $result = mysql_query($query) or die('Sorry, we could not count the number of results: ' . mysql_error()); $numberofresults = mysql_result($result, 0); $numberofresults = $numberofresults + 1; /*** query the database ***/ $i=1; /*** loop over the results ***/ while($i<$numberofresults) { $querySelect1 = "SELECT * FROM fonts WHERE id='$i'"; $resultSelect1 = mysql_query($querySelect1); $row2 = mysql_fetch_array($resultSelect1); /*** create the options ***/ echo '<option value="'.$row2['id'].'"'; if ($row2['id']==$font){ echo "selected='selected'"; } echo '>'.$row2['font']. '</option>'."\n"; $i++; } ?> Currently my site is still underdevelopment and I was having trouble creating a dynamically driven drop down to select which font the user wanted out of the selection that are available. I managed to get this to work just for proof of concept so I could move onto other things. Any help on how to get this to work in a more efficient manner would be greatly appreciated. Similar TutorialsHi I am trying to learn to clean coding and learning to clean old coding for any vulnerabilities. Can anyone help me with this code and see what I missed. I know theres a lot can anyone help so I can someday be able to do this myself easily please. Thanks for any and all help... Code: [Select] <? include("connect.php"); include("mail.php"); include("config.php"); function SendCounterMail($butlerstat1, $updatestat1) { $content1 = ''; $content1 .= "<font style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "</font><br>"."<br>". "<p align='center' style='font-size: 14px;font-family: Arial, Helvetica, sans-serif;font-weight:bold;'>Counter Information</p>". "<br>"."<table border='0' cellpadding='3' cellspacing='0' width='100%' align='center' class='style13'>"; if ( $butlerstat1 ) $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>Butler file is not running so it is now running by this process.</td></tr>"; if ( $updatestat1 ) $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>Records file is not running so it is now running by this process.</td></tr>"; $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>This mail is testing for check file running in.</td></tr></table>"; $subject = "Counter Information"; $from=$adminemailadd;//= "newuser@thissite.com"; $email = $adminemailadd; //SendHTMLMail($email, $subject, $content1, $from); } $butlerstat = FALSE; $updatestat = FALSE; $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); if ( mysql_num_rows($ressel) == 0 ) { mysql_free_result($ressel); mysql_query("Insert into auction_pause_management (referral_bids) values (1)"); $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); } $oldvalue1 = mysql_result($ressel, 0); mysql_free_result($ressel); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); if ( mysql_num_rows($ressel) == 0 ) { mysql_free_result($ressel); mysql_query("Insert into auction_pause_management (referral_bids) values (1)"); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); } $oldvalue = mysql_result($ressel, 0); mysql_free_result($ressel); sleep(2); $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); $newvalue1 = mysql_result($ressel, 0); mysql_free_result($ressel); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); $newvalue = mysql_result($ressel, 0); mysql_free_result($ressel); //if ( $oldvalue1 == $newvalue1 ) { $output1 = exec("php ".getcwd()."/update_butler.php >/dev/null &"); $butlerstat = TRUE; //} //if ( $oldvalue == $newvalue ) { $output = exec("php ".getcwd()."/update_records.php >/dev/null &"); $updatestat = TRUE; //} //SendCounterMail($butlerstat, $updatestat); //mysql_close($db); ?> I have approximately 50k-100k files in a directory. I'm running a script to check if any of the files are being used by the DB, if not then delete them. The problem is that I have made a quick test on a directory of just 1k files and it dies. Is there a way to optimize it? I know the script works, it's just that it takes too long to run. Even with just 1k files. And I'm pretty sure is the is_dir that's taking its sweet time. Any ideas? <?php require_once 'db_connect.php'; $default_dir = "storage/2011/"; if(!($dp = opendir($default_dir))) die("Cannot open $default_dir."); while($file = readdir($dp)) { if(is_dir($file)) { continue; } else if($file != '.' && $file != '..') { $query = "SELECT * FROM images Where filename = '".$file."' OR thumbname = '".$file."'"; $dbResult = mysql_query($query); $num_rows = mysql_num_rows($dbResult); if ($num_rows == 0){ unlink($default_dir.$file); echo $file."<br />"; } } } closedir($dp); ?> Hi
I have a small script, on a single file that needs to be optimized.
file is about 300 lines (16Kb), and basiccaly looks like the "PHP-monster" threw up on it.
Script is working ok, but surely could be much better.
PM if interested and I can send you a copy of file. If possible leave price/hourly rate.
I have created a form, that contains multiple text fields. When the user clicks on the Submit button, the form data should be populated in MySQL, I have programmed it in a way, that it works well, but the problem is, Since it contains so many text fields that collects the Manufacturer, Brand and so on repeatedly, I have created multiple queries to populate the DB. Here is the code, Code: [Select] <?php include("connect.php"); if (isset($_POST['confirm_order'])) { $o_manufacturer = trim(@$_POST['o_manufacturer']); $o_brand = trim(@$_POST['o_brand']); $o_type = trim(@$_POST['o_type']); $o_exp_date = trim(@$_POST['o_exp_date']); $o_qty = trim(@$_POST['o_qty']); $o_unit = trim(@$_POST['o_unit']); $o_unit_price = trim(@$_POST['o_unit_price']); $o_package = trim(@$_POST['o_package']); $o_package_price = trim(@$_POST['o_package_price']); $o_selling_price_perUnit = trim(@$_POST['o_selling_price_perUnit']); $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '$o_manufacturer', '$o_brand', '$o_type', '$o_exp_date', '$o_qty', '$o_unit', '$o_unit_price', '$o_package', '$o_package_price', '$o_selling_price_perUnit')"; $results = mysql_query($query); if ($results) { echo '<center><p class=small>Order updation successful, Click on LIST ORDERS button below to view the order entry.</p><br></center>'; echo '<center><a href="List_Orders.php" class="myButton">List Orders</a></center>'; } // Second Row Insertion if(!empty($_POST['o_manufacturer1'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer1']."' , '".$_POST['o_brand1']."' , '".$_POST['o_type1']."' , '".$_POST['o_exp_date1']."' , '".$_POST['o_qty1']."' , '".$_POST['o_unit1']."' , '".$_POST['o_unit_price1']."' , '".$_POST['o_package1']."' , '".$_POST['o_package_price1']."', '".$_POST['o_selling_price_perUnit1']."' )"; $results = mysql_query($query); } // Third Row Insertion if(!empty($_POST['o_manufacturer2'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer2']."' , '".$_POST['o_brand2']."' , '".$_POST['o_type2']."' , '".$_POST['o_exp_date2']."' , '".$_POST['o_qty2']."' , '".$_POST['o_unit2']."' , '".$_POST['o_unit_price2']."' , '".$_POST['o_package2']."' , '".$_POST['o_package_price2']."', '".$_POST['o_selling_price_perUnit2']."' )"; $results = mysql_query($query); } // Fourth Row Insertion if(!empty($_POST['o_manufacturer3'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer3']."' , '".$_POST['o_brand3']."' , '".$_POST['o_type3']."' , '".$_POST['o_exp_date3']."' , '".$_POST['o_qty3']."' , '".$_POST['o_unit3']."' , '".$_POST['o_unit_price3']."' , '".$_POST['o_package3']."' , '".$_POST['o_package_price3']."', '".$_POST['o_selling_price_perUnit3']."' )"; $results = mysql_query($query); } // Fifth Row Insertion if(!empty($_POST['o_manufacturer4'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer4']."' , '".$_POST['o_brand4']."' , '".$_POST['o_type4']."' , '".$_POST['o_exp_date4']."' , '".$_POST['o_qty4']."' , '".$_POST['o_unit4']."' , '".$_POST['o_unit_price4']."' , '".$_POST['o_package4']."' , '".$_POST['o_package_price4']."', '".$_POST['o_selling_price_perUnit4']."' )"; $results = mysql_query($query); } mysql_close(); } ?> Instead of posting the 'o_manufacturer ' value multiple times 'o_manufacturer1', 'o_manufacturer2', 'o_manufacturer3' and 'o_manufacturer4' I m looking for a code, that uses for loop or any other alternative ways that optimizes the code and works the proper way... NOTE : The file that i have attached is working 100% perfect, but I am looking for code optimization. Looking for help from experts.. Thanks a lot in advance... I've been searching for a science that will solve this analysis problem. Since I don't know what I'm looking for, I cannot properly express the task to accomplish.
I have an eCommerce store selling a product that has (let's keep it simple) three properties and each property can hold any one of three possible relevant values (or null).
Combinations: 3^3=27
A typical combination would be round/solid/blue, or cubic/squishy/white.
The task is to efficiently eliminate that part of the array if any particular {set of values} is null. That is, if I currently have no pink items, the relevant sections of the array would get eliminated.
Product variations with low n-values is easy to manually handle. But with five and above, that's the math(?) theory I am trying to know the name of.
(I wonder if any Matlab manuals would give a clue.)
I am trying this elimination of sections of an established array instead of rebuilding the array every time a value is locked in.
On the other hand, maybe I'm trying to be too smart about this and should just let the server do the grunt work over and over.
Hey.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? 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? Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys I am working to echo the results in a while or for loop... Both of my sample codes work, but the results are wrong! The while loop ONLY echos a result IF the first record in the postings table matches the id passed (does not display a result unless the first record has a match) The if loop displays ALL listings with the same name (counts them all) so there are no unique listings! <?php $posts_by_city_sql = "SELECT * FROM postings WHERE id='$_GET[id]'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); /* While Loop */ while($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } /* For Loop */ $posts_by_city_row = mysqli_fetch_array($posts_by_city_results); for ($i=0; $i<sizeof($posts_by_city_row); $i++) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } ?> Results with for loop (there are 7 total unique book names, but it's just counting the first match on id 7 times like below): AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners Good Evening - I am in the process of trying to call back a list of categories and sub categories using a WHILE LOOP inside of a WHILE LOOP. It works on a different part of the site within the admin panel but not here. Here it only calls one sub category and moves on to the next parent category instead of finishing the loop and pulling all sub categories out... // CATEGORIES $query = "SELECT * FROM cat"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $catid = $row['id']; $catname = $row['name']; $output .= "<li class=\"level0 nav-2 parent\" onmouseover=\"toggleMenu(this,1)\" onmouseout=\"toggleMenu(this,0)\"> <a href=\"product.php?cat=$catid\"> <span>$catname</span> </a>\n"; $querynav = "SELECT * FROM subcat WHERE pid = '$catid'"; $resultnav = mysql_query($querynav); while($array = mysql_fetch_array($resultnav, MYSQL_ASSOC)) { $subcatid = $row['id']; $subcatname = $row['name']; $output .= "<ul class=\"level0\"> <li class=\"level1 nav-2-1 first\"> <a href=\"product.php?cat=$catid&subid=$subcatid\"> <span>$subcatname</span> </a> </li> </ul> </li>"; } } Hi, I am new to PHP. Can someone explain me clearly how to use while loop inside while loop to print "*" in square shape. Thank you for your help. Code: [Select] <?php $hierachy = new hierachy; $iterator = new RecursiveIteratorIterator(new recursiveArrayIterator($hierachy->getLocalSubNodes($name1))); try { foreach($iterator as $key=>$value) { echo $value = substr($value,0,-1).'<br />'; } } catch(Exception $e) { echo $e->getMessage(); }?> I'm having a really bad brain fart and I cannot get the logic correct here lol. I need divs wrapped around every set of 5 images so if there is a total of 8 images then there would be 2 sets of divs (first with 5 images, second with 3 images) and if there was 12 images then there would be 3 sets of divs (first two with five images, last one with 2 images) etc etc What am I doing wrong and is there an easier way to do this? http://pastebin.com/QfsFxe4G Thanks! Hi.. I have while loop inside while loop but I encountered problem in displaying data inside while loop or the second while loop. here is my code: Code: [Select] <?php error_reporting(0); $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <script type="text/javascript"> function showDetails(pcode) { var clickElement = pcode.value; var click_id = pcode.id; // var value_ = document.getElementById(click_id).checked // = document.getElementById(clickElement).checked; //var Table = (document.getElementsByName('list')[0].value); var Table = document.getElementById('kanban_list'); var rows = Table.rows; var strSelect = document.getElementById(click_id).value; //alert(strSelect) for (var i = 0; i < rows.length; i++) { var row = rows[i]; //row.style.display = (row.id.substr(0,3) == strSelect) ? 'none' : ''; //row.style.display = (row.id.substr(0,3) == strSelect) ? // row.style.display = 'none'; // row.style.display = ''; if (row.id.substr(0,3) == strSelect) { row.style.display = ((document.getElementById(click_id).checked) == false) ? 'none' : '' } //(document.getElementById(click_id).checked == false) ? 'none' : '' : ''; } } </script> <?php $sql = "SELECT kc.PCODE, kc.count_wip_chemical_weighing, kc.count_wip_compounding, kc.count_wip_extrusion, kc.count_wip_forming, kc.count_wip_deflashing, kc.kanban, kc.virtual, p.max_lot, p.min_lot FROM kanban_checker kc JOIN plan p ON kc.PCODE = p.PCODE ORDER BY p.PCODE"; $result = mysql_query($sql, $con); ?><label>Display Details:</label><input onclick='showDetails(this);' id='chkDetail' type='checkbox' checked='checked' value='wip'/> <?php echo "<table id='kanban_list'>"; echo "<tr> <th> PCODE </th> <th> LOT CODE </th> <th> CHEMICAL WEIGHING </th> <th> COMPOUNDING </th> <th> EXTRUSION </th> <th> FORMING </th> <th> DEFLASHING </th> <th> KANBAN </th> <th> VIRTUAL </th> <th> MAX LOT </th> <th> MIN LOT </th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr> <td>$row[PCODE]</td> <td> </td> <!-- <td>$row[LOT_CODE]</td> --> <td>$row[count_wip_chemical_weighing]</td> <td>$row[count_wip_compounding]</td> <td>$row[count_wip_extrusion]</td> <td>$row[count_wip_forming]</td> <td>$row[count_wip_deflashing]</td> <td>$row[kanban]</td> <td>$row[virtual]</td> <td>$row[max_lot]</td> <td>$row[min_lot]</td> </tr>"; $sql = "SELECT kd.LOT_CODE, kd.wip_chemicalweighing, kd.wip_compounding, kd.wip_extrusion, kd.wip_forming, kd.wip_deflashing FROM kanban_data kd JOIN plan p ON kd.PCODE = p.PCODE ORDER BY p.PCODE "; $result_kanban_data = mysql_query($sql, $con); while($row_data = mysql_fetch_assoc($result_kanban_data)){ echo "<tr id='wip'> <td></td> <td> $row_data[LOT_CODE]</td> <td> $row_data[wip_chemicalweighing]</td> <td> $row_data[wip_compounding]</td> <td> $row_data[wip_extrusion]</td> <td> $row_data[wip_forming]</td> <td> $row_data[wip_deflashing]</td> </tr>"; } } echo "</table>"; ?> I attach the image of result from this code But the output that I want is all LOT_CODE with P35 PCODE will only display below P35 and all LOTCODE with P35M PCODE will only display below P35M. Thank you I hope somebody can help me.. A WHILE loop in a FOR loop problem Script about links and sublinks from 1 table. In fact 2 questions about that. 1) In the FOR loop I have for example to do the loop 3 times. (needs to find 3 results withing the loop with if and else) When first time, he's gonna search within the WHILE loop that holds (for example) 10 records of the DB in a variable. He needs to search for rowid number 5, he found it He goes out of the WHILE loop and goes searching again but now for rowid number 2 Now it seem that the WHILE loop start searching for number 2 but won't start from his first row in the variable (10 rows from the db ). He start at row number 6 instead of beginning all over again !!! -> so the order of the numbers of rows MUST be in an ascending order, ortherwise he won't find them all ! But the numbers I have are NOT in an ascending order !!! Why doesn't the WHILE loop begin again from his row 1 in the variable ? FOR loop { WHILE loop { content here, break; } } 2) even when I get all the result in an ascending order, he won't go doing a second search but with a different rowid number that he gets from the FOR loop. It is giving me back indeed the right new rowid number, but the WHILE loop is doing nothing. I have put many echo "..."; and other stuff for checking but can't find the cause ! Here's the code : Code: [Select] // $ResultShow = 10 rows from mysql db if(isset($ResultShow)){ if (mysql_num_rows($ResultShow) >= 1){ //$linksuborder = "2,3,4"; $array1 = explode(",", $linksuborder); sort($array1); for ($n = 0; $n < count($array1); $n++){ // searchin for the right row id in the variable $ResultShow where we find the numbers for next loop $r1 = each($array1); While($Row2 = mysql_fetch_array($ResultShow)) { if($Row2["linkid"] == $r1['value']) // found it, now look for the numbers that we'll put in an array { echo "---here the content---"; // linksuborder is where numbers from row id's are stored like 5,2,8 //now put them in an array $array2 = explode(",", $Row2["linksuborder"]); sort($array2); for ($n2 = 0; $n2 < count($array2); $n2++){ $r2 = each($array2); ////// here searching for the sublinks ////// While ($Row3 = mysql_fetch_array($ResultShow)) { if($Row3["linkid"] == $r2['value']) // search for the right row id within the variable $ResultShow { echo "---here the content---"; break; // found it, so no need to do the rest of the loop } // end if } //end while ////// end searching for sublinks ////// } // end for } // end if else { echo "--- content here ---"; } } // end while } // end for } //end if } // end if Table : linkid linksuborder linktitle 1 2,3,4 2 9,7,8 mainlink1 3 10 mainlink2 4 mainlink3 5 6 7 sublink3 8 sublink2 9 sublink1 10 sublink4 -> linksuborder 2,3,4 are the row id's for the mainlink -> than we put the numbers 9,8,7 (also row id's) mentioned in row linkid 2 also in a new array -> now we can search for the sublinks -> get the details from row linkid 9, than 7, than 8 -> First mainlink is compleet, now go to row linkid 3 to do it all over again for the next mainlink... RESULTS from an sorted array -> sort($linksuborder); ------------------------------------------------------------- mainlink1 : sublink1, sublink2, sublink3 mainlink2 : **no result back but it should * mainlink 3 : **no result back but it should * So I have a PHP parent page that is accesses that scans the database for the passed token in the URL and then replaces content on the template page using a loop. My issue is that I am trying to use a loop on the secondary page which causes the white screen of death. From what I can tell the loop inside a loop is causing the issue. I'll paste the code below, let a newbie know if you have any ideas or can point me in the right direction. Thanks everyone! Here is the chunk of code from the parent page with the loop function.... // output pre content eval("\$preContent = \"$preContent\";"); print_r( replaceChar($preContent) ); $sqlSearch = "SELECT * FROM ".$row[tdbd_name]." WHERE ".$sqlKeyword." LIMIT ".MAX_ROWS; $resultSearch = mysql_query($sqlSearch); while($displayrows = mysql_fetch_assoc($resultSearch)) { $display = replaceTokens($loopTemplate); $display = str_replace('\\', '[backslash]', $display); $display = str_replace('[%', '$displayrows[', $display); $display = addslashes(str_replace('%]', ']', $display)); $display = replaceTokens($display); $display = changeCase($display); eval("\$display = \"$display\";"); $display = stripslashes($display); $display = str_replace('[backslash]', '\\', $display); $display = replaceChar($display); print_r( $display ); } // output post content And here is the loop function from the page that the above code loops through replacing tokens in. <?php $mySQLServer = "xxxxxxxxx"; $mySQLUser = "xxxxxxxxxx"; $mySQLPass = "xxxxxxxx"; $mySQLDB = "xxxxxxxxxxxxx"; $SQLToday = date("m/d/y") . "<br />"; $SQLsevendays = mktime(0,0,0,date("n"),date("j")-7,date("Y")); $SQLsevenname = (date("l", $SQLsevendays)); $SQLsevennumber = (date("jS", $SQLsevendays)); $dbhandle = mssql_connect($mySQLServer, $mySQLUser, $mySQLPass) or die("Couldn't connect to SQL Server on $myServer"); $selected = mssql_select_db($mySQLDB, $dbhandle) or die("Couldn't open database $myDB"); $query = "WEB_ApproveHistory @State='CA', @Days=5, @Records=8"; $data = mssql_query($query); $result = array(); while ($row = mssql_fetch_object($data)) { $result[] = $row; $returnedresults = (97*($row->TotalApprovals)) ; } $englishreturnedresults = number_format($returnedresults); echo 'In just the last week since ' . $SQLsevenname . ' the ' . $SQLsevennumber . ' has delivered '; echo $englishreturnedresults; echo ' Here are just a few people '; echo '<ul class="BulletCheck">'; mssql_next_result($data); while ($row = mssql_fetch_object($data)) { $result[] = $row; echo '<li>' . ' ' . $row->FirstName . ' From '. $row->City . ', ' . $row->State .' PreApproved On ' .$row->ApprovedDate . '</li>'; } mssql_close($dbhandle); ?> Hey guys, I got some questions about the while loop It's dealing with the "qset" as you can see below: Code: [Select] $get = "SELECT qset from mailing_list where email = '$email'"; $result = mysqli_query($connect, $get) or die($connect); while ($row = mysqli_fetch_array($result)){ extract($row); $qset = rsort($row); $qset = (int)end($row); } if (empty($qset) || $qset < 1){ $qset = 1; return $qset; } elseif ($qset >=1){ $qset = $qset + 1; return $qset; } echo $qset; Nothing echoed out... Why? Also it seems like the script got stuck at the while loop, as no sql commands that follow up are processed Any help is appreciated! Thanks Hello. I have a simple SQL query that returns a list of names, this is good and all is right with the world. I would like to associate a number with each person, a RANDOM number that will change each time I call the page. Desired result:
Number | Name
18 | Jeff
2 | Tammy
12 | Steve
10 | Phil
5 | Michelle
etc. etc.
Pool of numbers will be from 1 to 30. Sometimes the names pool will result in 18 rows or 27 rows or any number in between. I just need to assign a number from 1 to 30 to each name that is not the same each time. Here's my loop.
while ($row= mysql_fetch_array($result)) { $lastname = $row["lastname"]; $firstname = $row["firstname"]; $numbers = range(1, 30); shuffle($numbers); foreach ($numbers as $number) { } echo "<tr> <td class='results'>$number</td> <td class='results'>$firstname $lastname</td> </tr>"; }Here's the problem I'm encountering: 1) If I leave the FOREACH inside the loop, I wind up with one or two repeated $number(s). 2) If I take the FOREACH outside the loop, I wind up with the first integer from the $numbers range repeated as many times as there are names I'm just not sure how to achieve a unique designation for each name. Could someone point me in the right direction? Thanks so much! Ok, I have a .csv file. the first key in the array is the name of the tables. the rest of the info is the data that needs to be put into my mysql database. Here is an example of what my array looks like. Array ( => Array ( => RECORD_TYPE [1] => BORROWER_FIRST_NAME [2] => BORROWER_MIDDLE_NAME [3] => BORROWER_LAST_NAME [4] => BORROWER_SUFFIX_NAME [5] => BORROWER_COMPANY_NAME [6] => LENDER [7] => LENDER_ADDRESS [8] => LENDER_CITY [9] => LENDER_STATE [10] => LENDER_ZIP [11] => LENDER_PHONE_NO [12] => TRUSTEE [13] => TRUSTEE_ADDRESS [14] => TRUSTEE_CITY [15] => TRUSTEE_STATE [16] => TRUSTEE_ZIP [17] => TRUSTEE_PHONE_NO [18] => PROPERTY_DESCRIPTION [19] => CASE_NO [20] => LOAN_NO [21] => LOAN_DOC_NO [22] => FORECLOSURE_DOC_NO [23] => FORECLOSURE_BOOK [24] => FORECLOSURE_PAGE [25] => PARCEL_ID_NO [26] => TRUSTEE_SALE_NUMBER [27] => SITUS_ADDRESS [28] => SITUS_UNIT_NO [29] => SITUS_CITY [30] => SITUS_COUNTY [31] => SITUS_STATE [32] => SITUS_ZIP [33] => APPRAISED_VALUE [34] => MINIMUM_BID [35] => JUDGMENT_AMOUNT [36] => LOAN_AMOUNT [37] => LOAN_BALANCE [38] => DATE_OF_LOAN [39] => INT_RATE [40] => PAYMENT [41] => MATURITY [42] => AUCTION_DATE [43] => AUCTION_TIME [44] => AUCTION_ADDRESS [45] => AUCTION_CITY [46] => LEGAL_DESCRIPTION [47] => RECORDING_DATE ) [1] => Array ( => T [1] => KATHLEEN [2] => [3] => PHILLIPS [4] => [5] => [6] => NATIONSTAR MORTGAGE, LLC [7] => JUST LAW, INC [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => [17] => [18] => COMM [19] => [20] => [21] => [22] => [23] => [24] => [25] => S1134120670 [26] => [27] => 11101 W. AMITY RD [28] => [29] => BOISE [30] => BOISE [31] => ID [32] => 83709 [33] => [34] => [35] => [36] => [37] => $91,325.12 [38] => [39] => 7.88% [40] => [41] => [42] => 9/10/2010 [43] => 11:00 AM [44] => 9465 W. EMERALD ST., STE. 260 [45] => BOISE [46] => COMMENCING AT THE NORTH QUARTER CORNER OF SECTION 34, TOWNSHIP 3 NORTH, RANGE 1 EAST [47] => 5/10/2010 ) [2] => Array ( => T [1] => ARNEL [2] => T [3] => BERMUDO [4] => [5] => [6] => NATIONSTAR MORTGAGE LLC [7] => JUST LAW, INC [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => [17] => [18] => RSFR [19] => [20] => [21] => [22] => [23] => [24] => [25] => [26] => [27] => 5718 N. MILLDAM PL [28] => [29] => GARDEN CITY [30] => BOISE [31] => ID [32] => 83714 [33] => [34] => [35] => [36] => [37] => $109,781.84 [38] => [39] => 6.88% [40] => [41] => [42] => 9/3/2010 [43] => 11:00 AM [44] => 9465 W. EMERALD ST., STE. 260 [45] => BOISE [46] => LOT 12 IN BLOCK 3 OF MILLSTREAM NO. 1 SUBDIVISION, ACCORDING TO THE PLAT THEREOF [47] => 5/10/2010 ) Here is the code that I am trying. Obviously its not working properly. $tablenames = $data2DArray[0]; unset($data2DArray[0]); $i=0; foreach ($tablenames as $tablename){ foreach($data2DArray as $datakey => $data){ echo "{$tablename}={$data[$i]}<br>"; } $i++; } -------------------------------------- Basically I need this to turn into a usable mysql insert query. Need to be able to insert into mysql_table set RECORD_TYPE='T', BORROWER_FIRST_NAME='KATHLEEN' etc I want to control the output of php code with if else statement like this. <?php if($row_director['director'] == "") {echo "";} else {echo " <table> <th> <h4>Directed by</h4> </th> <td> <h5> $row_director['director'] </h5> <br /> </td> </table> <br /> ";}?> I also want to loop through the results contained in $row_director['director'] Having tried various ways to achieve this, I have now given up. Can someone please help me. |