PHP - Loop Logical Problem
i have two tables assume question and answer
question table consists of Question_Date, Question_id and Question_title answer table consists of Answer_Date, Question_id, Answer_id and Answer_title let say i have 1000 records and i wish to display only the last 100 records combining both question and answer. How can i do this with loop..any suggestion would be appreciate thanks Similar TutorialsHi guys, i'm trying to increment a variable / session value whenever 'submit' comes in the POST. I can't seem to get around the logic of this. Code looks like this: Code: [Select] $var = 0 if($_POST('submit'){ $_SESSION['var2'] = $var++; } What I want it to do is increment the value of the session index everytime a user clicks 'submit'. But because i've reset $var to 0 everytime, it's always just going to stay at 1. I just can't think of a way to achieve this, does anyone have any clue on how I can? I made a bot, that scrapes content from a forum, i cant access the forum in work, so am trying to make something discreat to read it on my own site while at work. Anyway the links to threads are something like this. I got help and i know how to extract the unique thread number using regex. However i have a problem. What i really need, now that i think about it, is a way of getting the thread number and the thread title (so i can make sense of what im reading.) The thread title is in the setWindowStatus function. I cant think of a way to do it. I dont even know if it would work in an array what id basically like is something that says 1) Thread title - Thread id 2) Thread title - Thread id etc that is stored in a way that i can easily manipulate. Code: [Select] <img src="http://s2.images.proboards.com/xx.gif" alt=" " border="0"/></font></td><td class="windowbg" bgcolor="FFFFFF" width="48%" style="cursor:pointer;" onClick="if(!pb_bubble)location.href='/index.cgi?board=general&action=display&thread=13483';" onMouseOver="mouseOverHighlightCell(this);setWindowStatus('Lurkers, show your face ');return true; Okay i'm trying to compare these sets of variables. code looks like this.. Code: [Select] if( $row->cash > $finalcash && $row->core1 > $finalcore1 && $row->core2 > $finalcore2 && $row->core3 > $finalcore3 && $row->core4 > $finalcore4 ) { return true; } else { return false; } First question is this the appropriate way of doing this? Or would a nested if statement work better? example: Code: [Select] if ($row->cash > $finalcash) { if ($row->core1 > $finalcore1) { if ($row->core2 > $finalcore2) { if ($row->core3 > $finalcore3) { if ($row->core4 > $finalcore4) { } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } I know it looks pretty messy, so i'm wondering if anybody is aware of an alternative to achieving this? Hi there,
This may not be the correct space to post this - but I'm very new to all this.
I've created a page that will run a php script to output a query. I would then like to send that same query via email - however from a design perspective I don't think the correct process is to click 'submit' to view the query and then 'submit' to send the result via email?
Can you please advise on some design solutions regarding this issue?
Thanks!
im trying to make a salary system which would display a month salary according to login hours so i got two different tables storing data like
1. users table id, name, password, salary
2.attendance table id, user_id, Employee_Name, Remark, Login_Hours, Date
so what im looking to do is fetch all users id, name and salary from users table and then match it with attendance user_id,Employee_Name ,Login_Hours, table and then also count numbers of result for a particular year-month so that i could do the hourly wage calculation.
could someone help out i got no idea how to achieve it
apprieciate your help,
thanks
i tried something like this it does output something but still dunno how to match results of both tables and get result
$date = '2014-11'; $query1 = "SELECT COUNT(*) as num FROM attendance WHERE Date LIKE '%".$date."%' AND Employee_Name='moses'"; $total_pages = mysql_fetch_array(mysql_query($query1)); $total_res = $total_res[num]; // total rows counting of total office days of a month $result2=mysql_query("SELECT id, user_id, Employee_Name, Remark, SUM(Login_Hours), Date FROM attendance WHERE Employee_Name='moses'"); while($row = mysql_fetch_array($result2)){ echo $sal_to_month = 9000/$total_res; //9000 is salary should be fetched from users table echo '<br/>'; echo $sal_to_month/9*$row['SUM(Login_Hours)']; } In php is there a way to shortcut logical operators... example: Code: [Select] if ($row['CustomerSaas'] == 'Yes' && ($row['CustomerSaasPaidStatus'] == 'Trial' || $row['CustomerSaasPaidStatus'] == 'Trial Ended')) { to Code: [Select] if ($row['CustomerSaas'] == 'Yes' && ($row['CustomerSaasPaidStatus'] == 'Trial' || 'Trial Ended')) { fixed. 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 * I hate asking help twice in the same day but im really stuck Im having problem with this loop im writing. I'm randomly grabing a name from an array then im checking to make sure it doesnt exist already in the database if it does then it loops back and grabs another name. I'm having problems with seeing whats going on while its looping I inserted a name in the data base to match "AGENA" so if AGENA is the end result i know its not working. right now its not even looping. $planet_names = " AGENA Deneb Zuben Zosma"; $explode_names = explode(" ", $planet_names); $random_key_name = (array_rand($explode_names, 1)); $planet_name = $explode_names[$random_key_name]; $loop_again = 0; while ($loop_again > 1) { $name_check3 = "SELECT address FROM planets WHERE name = '".($planet_name)."'"; $name_check2 = mysql_query($name_check3) or trigger_error("SQL", E_USER_ERROR); $name_check1 = mysql_num_rows($name_check2); if($name_check1 >= "1"){ // checks to see if name exists $loop_again = 1; }else{ ++$loop_again; $planet_name = $planet_name; } } echo "It ran $loop_again times<br />"; echo "$name_check1 match found equals 1. No match found equals 0<br />"; echo $planet_name . "<br />"; All,
I am taking the output for every title in my Database and displaying it in a box. Within that box I am providing the opportunity to open another box with further content inside. The problem with the code below is that when you click on the expand button it expands in all the boxes, not just the one you are clicking in. I don't understand why this is happening when everything else is ok - any fixes and explanations are greatly appreciated:
// GOING THROUGH THE DATA if($result->num_rows > 0) { //echo "<hr />"; while($fetch=mysqli_fetch_array($result)) { $title=$fetch['title']; $feed_rss=$fetch['url']; $content_id=$fetch['content_id']; $source_image=$fetch['source_image']; $item_id = $fetch['item_id']; $item_title = $fetch['item_title']; $item_date = $fetch['fetch_date']; $item_description = $fetch['item_description']; $item_url = $fetch['item_url']; ///////////////////////////////////////////////////////////////////////////////// // ?> <div class="box col5"> <?php $query_string = "cid={$content_id}&t={$item_id}&item_title={$item_title}"; $url_query_string = "http://www.disciply.com/article/index.php?" . $query_string; /*Start of dynamic content open*/ echo "<p>$title</p>"; echo "<img src=$source_image />"; echo "<p>item_url = $item_url</p>"; ?> <div class="panel_button" style="display: visible;"><img src="../images/expand.png" alt="expand"/> <a href="#"><?php echo $item_title; ?></a></div> <div class="panel_button" id="hide_button" style="display: none;"><img src="../images/collapse.png" alt="collapse" /> <a href="#">Hide</a> <object type="text/html" data='<?php echo $item_url;?>' width="100%" height="800px" style="overflow:auto;border:5px ridge blue"> </object> </div> </div> Edited by genista, 19 July 2014 - 10:33 PM. Hello, I have a loop below but the first time the person isn't counted in the if loop... I'm new to php and I know there is something easy I'm missing but I can't see it! Any help you be great. Code: [Select] // loop from mysql reults while($row = mysql_fetch_array( $result )) { echo "Person: ".$row['id']; echo "Earned: ".$row['earned']; //set-up php var's $earnedSum = $row['earned']; $firstPerson = $row['id']; if ($lastPerson == $firstPerson){ $earnedTotal = $earnedTotal + $earnedSum ; // Add's the earn units $lastPerson = $firstPerson; }else{ $earnedTotal = 0 ; // reset $lastPerson = $firstPerson; } echo 'This is the total Earned Result = '.$earnedTotal.'<br>'; } ?> Hi! I have a code that don't do want I want that to do. <?php $chars = str_split('abc'); $char_len = count($chars); $length = 3; //loop for char_len^length $loop_length = pow($char_len, $length); for($i = 0; $i < $loop_length; $i++) { //convert $a to chars $string = ''; while($a != 0) { $string = $chars[$a % $char_len] . $string; $a = (int) ($a / $char_len); } //pad and print string echo str_pad($string, $length, $chars[0], STR_PAD_LEFT), "<br>\n"; if($loop_length-1 == $i){ $length++; } } ?> And what it do, is to print out all combination of a, b and c. My problem is that when the loop is done (you'll se my if statement) I want to add one on length so it print out a, b and c in four letters. ex abca, abcb. But it isen't working. Have you any clue that can help me? Thank you for your answer. Why does this code only display 1 result? If I PRINT $row3 all results diplay, but the variable will only give 1 result. It would be easier for me to just PRINT row3, but I have 13 rows with different loops. Code: [Select] $sql = "SELECT * FROM $city WHERE SG_Name='$sg GROUP BY ID'"; $result = mysql_query($sql); while ($row = mysql_fetch_row($result)) { $ID="{$row[3]}"; } "<tr border='1'> <td>".$Source_ID."</td> </tr>"; Hi guys, I have this code which fetches data from an existing database and reflects the data into a tabular form. Basically what it does is it parses the field portNumber from my table and gets the last two digits of the variable. Then it will highlight in the table all those returned values for portNumber. Here is the code: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Mapper</title> <script> function highlightRow(id) { document.getElementById(id).style.backgroundColor = "FFCC00"; } </script> <style> body { font-family:Tahoma, Geneva, sans-serif; font-size:10px; text-align:center; } .unitHere { color:#000; background-color:#0F0; styl } </style> </head> <body> <table width="800" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <th colspan="40" scope="col">SCMST 238</th> </tr> <tr> <?php $conn = mysql_connect("localhost", "root", "123456") or die(mysql_error()); mysql_select_db("orderstatus") or die(mysql_error()); $sql = mysql_query("SELECT * FROM superdome WHERE portNumber LIKE '%238%' AND isHistory='0' ORDER BY portNumber ASC") or die(mysql_error()); if(mysql_num_rows($sql) == 0) { echo "NOTHING FOUND"; } else { $i = 1; while ($i <= 40) { $x = 0; while($result = mysql_fetch_array($sql)) { $resultPortArray = str_split($result['portNumber'],4); $resultPortArray[1]; $x++; } if ($resultPortArray[1] == $i) { echo "<td width=\"20\" height=\"30\" id=\"".$i."\" class=\"unitHere\">".$i."</td>"; $i++; } else { echo "<td width=\"20\" height=\"30\" id=\"".$i."\">".$i."</td>"; $i++; } } } ?> </tr> </table> </body> </html> The problem is my output only highlights the one column in the array returned. The rest are not highlighted. I need help badly. This is the email verification script im using.. //email verify $activationKey = mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand(); $sql="INSERT INTO account_info (activation_key, status) VALUES ('$activationKey', 'verify')"; if (!mysql_query($sql)){ exit('Error: ' . mysql_error()); } else { //Send activation Email $to = $_POST['email']; $subject = "NarutoRPG.com Registration"; $message = "Welcome to our website! You, or someone using your email address, has completed registration at narutoRPG.com. You can complete registration by clicking the following link:\rhttp://www.arzania.com/verify.php?$activationKey\r\r If this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ narutoRPG.com Team"; $headers = 'From: ashyiscool2@gmail.com' . "\r\n" . 'Reply-To: ashyiscool2@gmail.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); //User isn't registering, check verify code and change activation code to null, status to activated on success $queryString = $_SERVER['QUERY_STRING']; $query = "SELECT * FROM account_info"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ if ($queryString == $row["activation_key"]){ echo "Congratulations!" . " " . $row["username"] . " is now the proud new owner of a NarutoRPG.com account. Login to begin to play."; $sql="UPDATE account_info SET activation_key = '', status='activated' WHERE (id = $row[id])"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } } } } } include "footer.php"; ?> For some reason, when the person is registered it shows everyones name who registered, for example.. You've been successfully registered!Congratulations! tonyhh is now the proud new owner of a NarutoRPG.com account. Login to begin to play.Congratulations! tonyh is now the proud new owner of a NarutoRPG.com account. Login to begin to play.Congratulations! tony is now the proud new owner of a NarutoRPG.com account. Login to begin to play.etc...etc.. How can you make it only repeat the users name who registered, not everyone? Hi Guys, I am trying update some array values in my database. For some reason using the code below the $checked and $counter values are not working. I have added the echos for debugging purposes and nothing is being echoed. $query = mysql_query("SELECT * FROM offers WHERE seller='$username' AND buyer='$buyer'"); while ($row = mysql_fetch_assoc($query)) { $checked = $_POST['checkbox'][$y]; $counter = $_POST['counter'][$y]; echo $checked; echo $counter; $date = date("Y-m-d"); $time = date("H:i:s"); mysql_query("UPDATE offers SET offer='$counter',seller_status='Counter Offer Made',buyer_status='Counter Offer Received',date='$date',time='$time',seller_action='0',buyer_action='1' WHERE domain='$checked'"); } When i do the following it echos the $checked and $counter values perfectly so i know that the form is posting ok. foreach ($_POST['checkbox'] as $checked) { echo $checked; } foreach ($_POST['counter'] as $counter) { echo $counter; } Can anybody figure out what is wrong with my while loop? Iv been at it for ages and cant seem to crack it. Thanks hi The output of this code is: 1950 1951 1952 .... script Code: [Select] <?php for ($i = 1950; $i < 2012; $i++) { echo "<option value='$i' class='dr'>".$i.'</option>'; } ?> but i need something like: Insert a date 1950 1951 1952 .... how can i solve that? welll. i can do <option value='null' class='dr'> year</option> this foreach loop is causing mysql_num_rows to not return the amount of rows in mysql correctly. the variable $value has two strings in it (testa and testb). So foreach should loop once with $value as 'testa', then loop again with $value as 'testb'. the problem is at the mysql_num_rows. It should return 1 because there is 1 row in mysql with keywords 'testa' and 1 row with keywords 'testb', instead it returns zero. If i change $value to 'testa' it works. Code: [Select] foreach($value as $value) { $updatestable = mysql_query("SELECT * FROM `Stacks` WHERE keywords LIKE '%$value%' ORDER BY id DESC LIMIT 1")or die (mysql_error()); $upnum = mysql_num_rows($updatestable); echo $upnum; if ($upnum==0){ $uporigin=0; } else { while($rowup = mysql_fetch_assoc($updatestable)) { $uporigin = $rowup['origin']; $upreply = $rowup['reply']; } } } hope the question isn't too complicated. basically if i remove the loop. the mysql num_rows works and returns a row. If i don't remove the loop it returns zero. I am trying to loop through a filtered table. This is the code of the loop:
$result = mysqli_query($con,$sql);
$query = "INSERT INTO invoiceitems(invnumber,itemnum,price,quantity) VALUES('$ttinvno','$itemno','$price','$qty')";#,unix_timestamp())";
if ($prebidder != $buser) { } ?> The filtered data has 55 rows of which 28 are unique. I am trying to loop through so that the names ($buser) match the invoice number ($ttinvno). I have the rows indexed on buser descending. But the rows don't seem to want to match correctly. The invoice numbers go in sequence correctly but for instance the first two rows have the same name. But no matter what I have done in this format either the invoice number changes after the first row, or it changes after the third row. I want it to change after the second row. I have tried multiple ways including prematurely defining row and then using mysqli_data_seek($result,0); to reset the result before the loop. Obviously there is a flaw in my code. Can anyone help? Thanks very much in advance!
|