PHP - Random Pagination Query
Can anyone explain what "of course you'll need to propagate the initial seed in the page requests" means in the following link?
http://stackoverflow.com/questions/4192284/random-values-in-mysql-query-with-pagination Similar TutorialsHi Guys I need some help this is my first real php website. Im trying to retrieve results from an accommodation database, to make the results fair I need to return a random set of results so each accommodation get a fair viewing and nobody is always at the bottom. The problem arises when i paginate the results, because each page executes a separate randomly ordered offset mysql query I can end up showing the some of the same results over and over on multiple pages. This is going to confuse and irritate searchers. How can i achieve results and paginate them where each accommodation gets a fair chance at the first page each time the database is searched? Hi im having a little trouble with pagination its not letting me use this username verification as well as the forum? Any help would be appreciated! <? if(!session_is_registered("username")){ echo "<p> </p> <form name='login' method='post' action='register.php'> <table border='0' width='400' align='center'> <tr> <td width='90'>Username:</td> <td width='300'><input type='text' name='username' /></td> </tr> <tr> <td width='90'>Password:</td> <td width='300'><input type='password' name='password' /></td> </tr> <tr> <td width='90'>Email:</td> <td width='300'><input type='text' name='email' maxlength='100' /></td> </tr> <tr> <td>Gender: </td><td><input name='gender' type='radio' value='male' /> Male <input name='gender' type='radio' value='female' /> Female</td></tr> <tr> <td width='90'> </td> <td width='300'> <p align='left'><input type='submit' name='submit' value='Submit'></p> </td> </tr> </table> </form>"; }else{ include 'connect.php'; // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM newtopic"; $result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 10; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; // get the info from the db $sql = "SELECT * FROM newtopic LIMIT $offset, $rowsperpage"; $result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR); echo "<table width='371' border='0' align='center'> <tr> <td height='50' colspan='2'><b> Fight Talk </b><input name='forumtype' type='hidden' value='fighttalk' /></td> </tr> <tr> <td width='160' height='50' align='center' colspan='2'><a href='fighttalknewtopic.php'># New Topic</a></td> </tr> <tr> <td><b>Username:</b></td><td><b>Message:</b></td> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . " <b> " . $row['username'] . "</b><br />" . $row['date'] . " : " . $row['time'] . "</td>";; echo "</td>"; echo "<td>" . $row['title'] . "</td>"; echo "</tr><tr>"; echo "<td colspan='2'>" . $row['message'] . "</td>"; echo "</tr>"; } echo "</table>"; /****** build the pagination links ******/ // range of num links to show $range = 3; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'>First</a> "; // get previous page num $prevpage = $currentpage - 1; echo " - "; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>Next</a> "; echo " - "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>Last</a> "; } // end if /****** end build pagination links ******/ ?> Sorry about the long code but this is the part it errors with: <? if(!session_is_registered("username")){ echo "<p> </p> <form name='login' method='post' action='register.php'> <table border='0' width='400' align='center'> <tr> <td width='90'>Username:</td> <td width='300'><input type='text' name='username' /></td> </tr> <tr> <td width='90'>Password:</td> <td width='300'><input type='password' name='password' /></td> </tr> <tr> <td width='90'>Email:</td> <td width='300'><input type='text' name='email' maxlength='100' /></td> </tr> <tr> <td>Gender: </td><td><input name='gender' type='radio' value='male' /> Male <input name='gender' type='radio' value='female' /> Female</td></tr> <tr> <td width='90'> </td> <td width='300'> <p align='left'><input type='submit' name='submit' value='Submit'></p> </td> </tr> </table> </form>"; }else{ Also does anyone know how I can center the the "First - Previous 1-2-3-4 Next - Last" part of the pagination script? Thanks for the help Hi all I have written a bit of code that I need to change from 4 seperate SQL queries into 1 so I can paginate the results. My code is below: Code: [Select] <!-- Get Trader premium adverts --> <?php $gettraderads = mysql_query("SELECT * FROM `trade-adverts` WHERE type = 'premium' AND paid = 1 AND categoryid = 1 AND live = 1 AND approved = 1 AND dateexpired >= '".$todaysdate."' ORDER BY id DESC "); $numtraderads = mysql_num_rows($gettraderads); while ($showtraderads = mysql_fetch_array($gettraderads)) { include('trader-ad-cell.php'); } ?> <!-- Get Trader standard adverts --> <?php $gettraderads = mysql_query("SELECT * FROM `trade-adverts` WHERE type = 'standard' AND categoryid = 1 AND live = 1 AND approved = 1 AND dateexpired >= '".$todaysdate."' ORDER BY id DESC "); $numtraderads = mysql_num_rows($gettraderads); while ($showtraderads = mysql_fetch_array($gettraderads)) { include('trader-ad-cell.php'); } ?> <!-- Get premium adverts --> <?php $getads = mysql_query("SELECT * FROM `adverts` WHERE categoryid = 1 AND type = 'premium' AND paid = 1 AND live = 1 AND approved = 1 AND dateexpired >= '".$todaysdate."' ORDER BY id DESC "); while ($showads = mysql_fetch_array($getads)) { include('ad-cell.php'); } ?> <!-- Get standard adverts --> <?php $getads = mysql_query("SELECT * FROM `adverts` WHERE categoryid = 1 AND type = 'standard' AND live = 1 AND approved = 1 AND dateexpired >= '".$todaysdate."' ORDER BY id DESC "); while ($showads = mysql_fetch_array($getads)) { $standarduserid = $showads['userid']; $getstandarduserinfo = mysql_query(" SELECT * FROM `users` WHERE id = '".$standarduserid."'"); $showstandarduserinfo = mysql_fetch_array($getstandarduserinfo); include('standard-ad-cell.php'); } ?> Can anyone help me? Many thanks Pete I had originally created a topic on my pagination not working, but I found out what the problem was. The topic I had created was irrelevant to what the problem was... but anyway, here's my situation: I've got a query that searches in a MySQL table for a certain value. Then it list's all the findings in a table (pretty simple). Anyway, I obviously want to have a pagination system to make it easier to manage the amount of data per page. The pagination works fine, it's used for another query that just pulls data (so NO WHERE clause is used!). That is what is causing the problem. I spent hours trying to figure out why this is happening, then I figured out that the only difference between the pagination that works and the one that doesn't is the query have the where clause. What happens when the where clause is used is that the pagination works fine on the first page, but if you click the link to go to a different page, the page is empty and turns up no results so the mysql data that is pulled is lost. So here is my code. I don't know exactly why the where clause causes the pagination to not work. Code: [Select] $conn = mysql_connect("$mysql_host","$mysql_user","$mysql_password") or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db("$mysql_database",$conn) or trigger_error("SQL", E_USER_ERROR); // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM ACTIVE WHERE MODEL='$model'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 5; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; $sql = "SELECT * FROM ACTIVE WHERE MODEL='$model' ORDER BY INDEX_ID DESC LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or die('Error: ' . mysql_error()); echo " <table width=100% align=center border=1 class=\"mod\"><tr> <td align=center bgcolor=#00FFFF><b>Rating</b></td> <td align=center bgcolor=#00FFFF><b>Title</b></td> <td align=center bgcolor=#00FFFF><b>Make/Model</b></td> <td align=center bgcolor=#00FFFF><b>Type</b></td> <td align=center bgcolor=#00FFFF><b>Difficulty</b></td> <td align=center bgcolor=#00FFFF><b>Comments</b></td> <td align=center bgcolor=#00FFFF><b>Views</b></td> </tr>"; while ($row = mysql_fetch_assoc($result)) { { // Begin while $title = $row["TITLE"]; $type = $row["TYPE"]; $difficulty = $row["DIFFICULTY"]; $comments = $row["COMMENT_TOTAL"]; $id = $row['INDEX_ID']; $rating = $row["RATING_AVERAGE"]; $make = $row["MAKE"]; $model = $row["MODEL"]; $views = $row["HITS"]; echo " <tr> <td>$rating/10</td> <td><a href=\"mod.php?id=$id\">$title</a></td> <td>$make - $model</td> <td>$type</td> <td>$difficulty</td> <td>$comments</td> <td>$views</td> </tr>"; } } echo "</table><br />"; /****** build the pagination links ******/ echo "<center>"; // range of num links to show $range = 3; echo "<i>Page: </i>"; // if not on page 1, don't show back links if ($currentpage > 1) { // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a stylehref='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> - "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " - <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>Next</a> "; } // end if /****** end build pagination links ******/ mysql_close($conn); } echo "$pagination</center>"; ?> I really appreciate the help! Thanks. I want a simple function that converts a sql query into two queries for pagination purposes. So if the sql query is "SELECT `Name` FROM table1" I would like to perform: "SELECT COUNT(*) FROM table 1" and "SELECT `Name` FROM table1 LIMIT 10, 20" (example) (1) Would this work for most basic queries? (obviously if LIMIT wasn't already used)? (2) What command would I use to convert "SELECT `Name` FROM table1" to "SELECT COUNT(*) FROM table 1" I am aware there is more involved than this, but am just interested in the query side of things. Hi there I adapted the pagination tutorial from here on PHP Freaks so that it can deal with a db query. The pagination itself works just fine but I have a small issue, hopefully someone can help me please. I have set up the query so that it won't allow blank searches. The script works perfectly well without the pagination. With the pagination, the script now returns a few results as well as the 'you didn't enter a search-term' message - can someone help me tidy it up please? I'm guessing that I've put the search=$search term in too many places in the pagination script. This is the query Code: [Select] if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 1) { $error[] = '<div class="messagebox">You didn\'t specify a search term</div></div>'; $error[] = '<div class="small"><a href="search2.php"><p>Search Again?</p></a></div>'; } else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } $sql = "SELECT * FROM pro_words WHERE word LIKE '%{$searchTermDB}%' ORDER BY word LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $num_rows = mysql_num_rows($result); //display results if (mysql_num_rows($result) < 1) { $error[] = '<div class="messagebox">Sorry, your search term yielded no results.</div>'; $error[] = '<div class="small"><a href="search.php"><p>Search Again?</p></a></div>'; } else { echo '<div class="messagebox">Here are your search results.</div>'; while ($list = mysql_fetch_array($result)) { // echo data echo '<div class="small"><a href="word.php?w=' . $list['word'] . '">' . $list['word'] . '</a></div>'; } //end while } } This is the pagination Code: [Select] // range of num links to show $range = 3; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?search=$search¤tpage=1'><<</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?search=$search¤tpage=$prevpage'><</a> "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?search=$search¤tpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?search=$search¤tpage=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?search=$search¤tpage=$totalpages'>>></a> "; } Thanks in advance for any help. Hi, I am trying to create a view where the user can sort by any column. What I have made so far works great, but when it comes to pagination, which I will be trying soon, I foresee a problem . The thing is, my code gets data out of a database and puts it into a multidimensional array, which is sorted using afew array sorting functions. It is a query that drives the main loop, and inside that loop are other queries that get various data from other tables, which is where the problem lies when coming to sort with pagination. What I would like to know is how would I build a myslq query that can accomplish the same thing as my code, but do away with the need for the arrays? My code is here, sorry about it being so long: <?PHP if($_POST['targetid']) { $box = array() ; if($_POST['type']) { $extra = 'AND entity_details.typeRef = ?' ; $targetType = $_POST['type'] ; } $sortMode = $_POST['sortmode'] ; $targetUser = $_POST['targetid'] ; include('pdoconnect.php') ; $result = $dbh->prepare("SELECT entity_details.name, entity_contacts.name AS cName, entity_contacts.id, entity_details.countryRef FROM entity_details, entity_contacts WHERE entity_contacts.isPrimary = 1 AND entity_contacts.entityRef = entity_details.id $extra AND entity_details.ownerRef = ?") ; if($extra) { $result->bindParam(1, $targetType, PDO::PARAM_INT) ; $result->bindParam(2, $targetUser, PDO::PARAM_INT) ; } else $result->bindParam(1, $targetUser, PDO::PARAM_INT) ; $result->execute() ; $count = $result->rowCount() ; if($count > 0) { echo "Showing " ; if($targetType == 2) echo "prospects!" ; elseif($targetType == 3) echo "customers!" ; elseif($targetType == 4) echo "leads!" ; else echo "everything." ; echo '<br />' ; } if($count > 0) { $mode = $_GET['sort'] ; echo "<div class='row'>\n" ; echo "<div class='cell'>" ; if($sortMode != 'name') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'name');\">Name</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrname');\">Name</a>" ; echo "</div>" ; echo "<div class='cell'>" ; if($sortMode != 'contact') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'contact');\">Contact</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrcontact');\">Contact</a>" ; echo "</div>" ; echo "<div class='cell'>" ; if($sortMode != 'email') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'email');\">Email</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rremail');\">Email</a>" ; echo "</div>" ; echo "<div class='cell'>" ; if($sortMode != 'tel') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'tel');\">Tel</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrtel');\">Tel</a>" ; echo "</div>" ; echo "<div class='cell'>" ; if($sortMode != 'payment') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'payment');\">Payment Terms</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrpayment');\">Payment Terms</a>" ; echo "</div>" ; echo "<div class='cell' style='width:30px;'>" ; if($sortMode != 'currency') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'currency');\">Cur</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrcurrency');\">Cur</a>" ; echo "</div>" ; echo "<div class='cell'>" ; if($sortMode != 'country') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'country');\">Country</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrcountry');\">Country</a>" ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; if($sortMode != 'lastc') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'lastc');\">Last Contacted</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrlastc');\">Last Contacted</a>" ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; if($sortMode != 'lastm') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'lastm');\">Last Marketed</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrlastm');\">Last Marketed</a>" ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; if($sortMode != 'lastd') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'lastd');\">Last Deal</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrlastd');\">Last Deal</a>" ; echo "</div>" ; echo "<div class='cell' style='width:50px;'>" ; if($sortMode != 'cltv') echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'cltv');\">CLTV</a>" ; else echo "<a onclick=\"traderSelectCustomer('$targetUser', '$targetType', 'Rrcltv');\">CLTV</a>" ; echo "</div>" ; echo "</div>\n" ; } else { echo "You have no " ; if($targetType == 2) echo "prospects!" ; elseif($targetType == 3) echo "customers!" ; elseif($targetType == 4) echo "leads!" ; else echo "nothing!" ; } while($row = $result->fetch(PDO::FETCH_ASSOC)) { $id = $row['id'] ; $countryid = $row['countryRef'] ; // Get primary contact data. $resultName = $dbh->prepare("SELECT entity_contacts_emails.email, entity_contacts_telephones.tel FROM entity_contacts_emails, entity_contacts_telephones WHERE entity_contacts_emails.contactRef = ? AND entity_contacts_telephones.contactRef = ? LIMIT 1") ; $resultName->bindParam(1, $id, PDO::PARAM_INT) ; $resultName->bindParam(2, $id, PDO::PARAM_INT) ; $resultName->execute() ; $rowName = $resultName->fetch(PDO::FETCH_ASSOC) ; /////////////////////////// // Get country. $resultCountry = $dbh->prepare("SELECT country FROM countries WHERE id = ? LIMIT 1") ; $resultCountry->bindParam(1, $countryid, PDO::PARAM_INT) ; $resultCountry->execute() ; $rowCountry = $resultCountry->fetchColumn() ; /////////////////////////// // Get currencies dealt with. $resultCurrencies = $dbh->prepare("SELECT currencies.symbol FROM entity_currencies_dealt, currencies WHERE entity_currencies_dealt.currencyRef = currencies.id AND entity_currencies_dealt.entityRef = ?") ; $resultCurrencies->bindParam(1, $id, PDO::PARAM_INT) ; $resultCurrencies->execute() ; while($rowCurrencies = $resultCurrencies->fetch(PDO::FETCH_ASSOC)) { $currencyString .= $rowCurrencies['symbol'] . " " ; } /////////////////////////// // Get payment terms. $resultTerms = $dbh->prepare("SELECT entity_payment_terms.term FROM entity_details, entity_payment_terms WHERE entity_details.paymentTermsRef = entity_payment_terms.id AND entity_details.id = ?") ; $resultTerms->bindParam(1, $id, PDO::PARAM_INT) ; $resultTerms->execute() ; $resultTerms = $resultTerms->fetchColumn() ; /////////////////////////// // Get last contacted. $resultLastCon = $dbh->prepare("SELECT DATE(date) FROM contact_method_history WHERE id = ? ORDER BY date LIMIT 1") ; $resultLastCon->bindParam(1, $id, PDO::PARAM_INT) ; $resultLastCon->execute() ; $resultLastCon = $resultLastCon->fetchColumn() ; /////////////////////////// // Get last enquired. $resultLastEnq = $dbh->prepare("SELECT DATE(dateCreated) FROM entity_enquiries WHERE entityRef = ? ORDER BY DATE(dateCreated) LIMIT 1") ; $resultLastEnq->bindParam(1, $id, PDO::PARAM_INT) ; $resultLastEnq->execute() ; $resultLastEnq = $resultLastEnq->fetchColumn() ; /////////////////////////// array_push($box, array(rawurldecode($row['name']), rawurldecode($row['cName']), $rowName['email'], $rowName['tel'], $resultTerms, trim($currencyString), $rowCountry, $resultLastCon, $resultLastEnq)) ; $currencyString = '' ; } } $i = 0 ; function subval_sort($a, $subkey, $mode) { foreach($a as $k=>$v) { $b[$k] = strtolower($v[$subkey]); } if(strstr($mode, 'Rr')) arsort($b); else asort($b); foreach($b as $key=>$val) { $c[] = $a[$key]; } return $c; } if($sortMode == 'name' || $sortMode == 'Rrname') $x = 0 ; if($sortMode == 'contact' || $sortMode == 'Rrcontact') $x = 1 ; if($sortMode == 'email' || $sortMode == 'Rremail') $x = 2 ; if($sortMode == 'tel' || $sortMode == 'Rrtel') $x = 3 ; if($sortMode == 'payment' || $sortMode == 'Rrpayment') $x = 4 ; if($sortMode == 'currency' || $sortMode == 'Rrcurrency') $x = 5 ; if($sortMode == 'country' || $sortMode == 'Rrcountry') $x = 6 ; if($sortMode == 'lastc' || $sortMode == 'Rrlastc') $x = 7 ; if($sortMode == 'laste' || $sortMode == 'Rrlaste') $x = 8 ; if($count > 0) $box = subval_sort($box, $x, $sortMode); foreach($box as $row) { echo "<div class='row'>\n" ; echo "<div class='cell'>" ; echo $row[0] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[1] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[2] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[3] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[4] ; echo "</div>" ; echo "<div class='cell' style='width:30px;'>" ; echo $row[5] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[6] ; echo "</div>" ; echo "<div class='cell'>" ; echo $row[7] ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; echo $row[8] ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; echo $row[9] ; echo "</div>" ; echo "<div class='cell' style='width:100px;'>" ; echo $row[10] ; echo "</div>" ; echo "<div class='cell' style='width:50px;'>" ; echo $row[11] ; echo "</div>" ; echo "</div>\n" ; } ?> I know maybe it can be done using many subqueries(?) but I am pretty average at MySQL. Can anyone tell me how? I've got a page with pagination set up, but I can't figure out where I went wrong with the links at the bottom. When I do a search, it generates the proper number of links, but clicking on the links goes to a page with a whole row of 20 links at the bottom and no results on the page. (my search should show 3 pages with 2 records on each page) I've looked through the tutorial here and one in a book on pagination. Not seeing what's wrong. I'd narrow this down if I knew where it was causing the problem. pagination links are at the very bottom of the code. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>search.html</title></head> <body> <center> <p>The results of your search:</p> <br> </center> require ('databaseconnect.php'); $select = mysql_select_db($db, $con); if(!$select){ die(mysql_error()); } $display = 2; if (isset($_GET['np'])) { $num_pages = $_GET['np']; } else { $data = "SELECT COUNT(*) FROM descriptors LEFT JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE `leaf_shape` LIKE '%$select1%' AND `leaf_venation` LIKE '%$select3%' AND `leaf_margin` LIKE '%$select4%'"; $result = mysql_query ($data); if (!$result) { die("Oops, my query failed. The query is: <br>$data<br>The error is:<br>".mysql_error()); } $row = mysql_fetch_array($result, MYSQL_NUM); // row 41 $num_records = $row[0]; if ($num_records > $display) { $num_pages = ceil ($num_records/$display); } else { $num_pages = 1; } } if (isset($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } if(isset($_POST[submitted])) { // Now collect all info into $item variable $shape = $_POST['select1']; $color = $_POST['select2']; $vein = $_POST['select3']; $margin = $_POST['select4']; // This will take all info from database where row tutorial is $item and collects it into $data variable row 55 $data = mysql_query("SELECT `descriptors`.* ,`plantae`.* FROM `descriptors` LEFT JOIN `plantae` ON (`descriptors`.`plant_id` = `plantae`.`plant_name`) WHERE `leaf_shape` LIKE '%$select1%' AND `leaf_venation` LIKE '%$select3%' AND `leaf_margin` LIKE '%$select4%' ORDER BY `plantae`.`scientific_name` ASC LIMIT $start, $display"); //chs added this in... row 72 echo '<table align="center" cellspacing="0" cellpading-"5"> <tr> <td align="left"><b></b></td> <td align="left"><b></b></td> <td align="left"><b>Leaf margin</b></td> <td align="left"><b>Leaf venation</b></td> </tr> '; // This creates a loop which will repeat itself until there are no more rows to select from the database. We getting the field names and storing them in the $row variable. This makes it easier to echo each field. while($row = mysql_fetch_array($data)){ echo '<tr> <td align="left"> <a href="link.php">View plant</a> </td> <td align="left"> <a href="link.php">unknown link</a> </td> <td align="left">' . $row['scientific_name'] . '</td> <td align="left">' . $row['common_name'] . '</td> <td align="left">' . $row['leaf_shape'] . '</td> </tr>'; } echo '</table>'; } if ($num_pages > 1) { echo '<br /><p>'; $current_page = ($start/$display) + 1; // row 100 if ($current_page != 1) { echo '<a href="leafsearch2a.php?s=' . ($start - $display) . '&np=;' . $num_pages . '">Previous</a> '; } for ($i = 1; $i <= $num_pages; $i++) { if($i != $current_page) { echo '<a href="leafsearch2a.php?s=' . (($display * ($i - 1))) . '$np=' . $num_pages . '">' . $i . '</a>'; } else { echo $i . ' '; } } if ($current_page != $num_pages) { echo '<a href="leafsearch2a.php?s=' . ($start + $display) . '$np=' . " " . $num_pages . '"> Next</a>'; } } ?> </body></html> I want to select 20 sites randomly. But when I generate a random number and use it in my query to extract the site information. But if an ID doesn't exist with that random number, it doesn't display information. How can this be fixed? $amount_get = mysql_query("SELECT id FROM users"); $random = rand(0,mysql_num_rows($amount_get)); for($amount = $random; $amount > 30; $amount = $random) { $query = mysql_query("SELECT site_url,username,id FROM users WHERE id='$amount' LIMIT 150"); $data_grab = mysql_fetch_assoc($query); echo $data_grab['site_url']."<input type='submit'>"; } I've followed the PHP Freaks pagination tutorial which you can find here. And I also got it to work, the only problem is that the script won't work when I use the query outside of the function. Here's the function: <?php function knuffix_list ($query, $dbc) { // find out how many rows are in the table: $query_row = "SELECT COUNT(*) FROM con"; $query_run = mysqli_query ($dbc, $query_row); $row = mysqli_fetch_row($query_run); $num_rows = $row[0]; // number of rows to show per page $rows_per_page = 5; // find total pages -> ceil for rounding up $total_pages = ceil($num_rows / $rows_per_page); // get the current page or set a default if (isset($_GET['current_page']) && is_numeric($_GET['current_page'])) { // make it an INT if it isn't $current_page = (int) $_GET['current_page']; } else { // default page number $current_page = 1; } // if current page is greater than total pages then set current page to last page if ($current_page > $total_pages) { $current_page = $total_pages; } // if current page is less than first page then set current page to first page if ($current_page < 1) { $current_page = 1; } // the offset of the list, based on current page $offset = (($current_page - 1) * $rows_per_page); echo "test " . $query; // SCRIPT ONLY WORKS IF I INSERT QUERY HERE $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT $offset, $rows_per_page"; $data = mysqli_query ($dbc, $query) or die (mysqli_error ($dbc)); // Loop through the array of data while ($row = mysqli_fetch_array ($data)) { global $array; // Variables for the table $con_id = $row['con_id']; $likes_count = $row['likes']; $dislikes_count = $row['dislikes']; $dbuser_name = $row['nickname']; $dbuser_avatar = $row['avatar']; $user_id = $row['user_id']; // The TABLE echo "<table padding='0' margin='0' class='knuffixTable'>"; echo "<tr><td width='65px' height='64px' class='avatar_bg' rowspan='2' colpan='2'><img src='avatar/$dbuser_avatar' alt='avatar' /></td>"; echo "<td class='knuffix_username'><strong><a href='profile.php?user=$dbuser_name' title='Profile of $dbuser_name'>" . $dbuser_name . "</a> ___ " . $user_id . "____ <form action='' method='POST'><button type='submit' name='favorite' value='fav'>Favorite</button></form>"; echo "</strong><br />" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . "</td></tr><tr><td>"; echo "<form action='' method='post'> <button class='LikeButton' type='submit' name='likes' value='+1'>Likes</button> <button class='DislikeButton' type='submit' name='dislikes' value='-1'>Dislikes</button> <input type='hidden' name='hidden_con_id' value='" . $con_id . "' /> </form></td><td class='votes'>Y[" . $likes_count . "] | N[" . $dislikes_count . "]</td></tr>"; echo "<tr><td class='knuffix_name' colspan='3'><strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td colspan='2' class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "</table>"; // POST BUTTONS inside the table $likes = $_POST['likes']; $dislikes = $_POST['dislikes']; $con_id = $_POST['hidden_con_id']; $favorite = $_POST['favorite']; $array = array ($likes, $dislikes, $con_id, $user_id, $favorite); } /********* build the pagination links *********/ // BACKWARD // if not on page 1, show back links and show << link to go back to the very first page if ($current_page > 1) { echo " <a href='{$_SERVER['PHP_SELF']}?current_page=1'><<</a> "; // get previous page number and show < link to go to previous $prev_page = $current_page - 1; echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$prev_page'><</a> "; } // CURRENT // range of number of links to show $range = 3; // loop to show links in the range of pages around current page for ($x = ($current_page - $range); $x < (($current_page + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $total_pages)) { // if we're on current page if ($x == $current_page) { // highlight it but don't make a link out of it echo "[<b>$x</b>]"; // if it's not the current page then make it a link } else { echo "<a href='{$_SERVER['PHP_SELF']}?current_page=$x'>$x</a>"; } } } // FORWARD // if not on the last page, show forward and last page links if ($current_page != $total_pages) { // get next page $next_page = $current_page + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$next_page'>></a> "; // echo forward link for last page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$total_pages'>>></a> "; } /***** end building pagination links ****/ mysqli_close($dbc); } ?> As you can see above, the script will only work if I put the query right below the $offset variable and above the $data variable. I put the test echo above the query to see how the query looks like when I induce the query from the outside through the function parenthesis into the function, and this is what I get printed out: test SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT , Obviously the $offset and the $rows_per_page variables are not set, when I induce the query from the outside into the function. So in that sense my question is: How can I induce the query from the outside into the function SO THAT the $offset and the $rows_per_page variables are set as well and NOT empty? p.s. I need the query outside of the function because I'm using a sort by category functionality. As above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads 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 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> Say I have this query: site.com?var=1 ..I have a form with 'var2' field which submits via get. Is there a way to produce: site.com?var=1&var2=formdata I was hoping there would be a quick way to affix, but can't find any info. Also, the query could sometimes be: site.com?var2=formdata&var=1 I would have to produce: site.com?var2=updatedformdata&var=1 Is my only option to further parse the query? I was just wondering if it's possible to run a query on data that has been returned from a previous query? For example, if I do Code: [Select] $sql = 'My query'; $rs = mysql_query($sql, $mysql_conn); Is it then possible to run a second query on this data such as Code: [Select] $sql = 'My query'; $secondrs = mysql_query($sql, $rs, $mysql_conn); Thanks for any help I'm trying to update every record where one field in a row is less than the other. The code gets each row i'm looking for and sets up the query right, I hope I combined the entire query into one string each query seperated by a ; so it's like UPDATE `table` SET field2= '1' WHERE field1= '1';UPDATE `table` SET field2= '1' WHERE field1= '2';UPDATE `table` SET field2= '1' WHERE field1= '3';UPDATE `table` SET field2= '1' WHERE field1= '4';UPDATE `table` SET field2= '1' WHERE field1= '5'; this executes properly if i run the query in phpMyAdmin, however when I run the query in PHP, it does nothing... Any advice? I can't get my head around it, no matter how many tutorials I read.. So would anyone be able to put this code into a pagination of 3 per page? Many Thanks Code: [Select] <?php if(!$_GET['id']) { $query = "SELECT * FROM news where published = '1' ORDER by id DESC"; $result = mysql_query($query) or die(mysql_error()); $news = mysql_fetch_assoc($result); ?> <?php do { ?> <table width="590" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="2"><h2><? echo $news['title']; ?></h2></td> </tr> <tr> <td width="398"><? echo $news['story']; ?></td> <td width="192"><img src="<? echo $news['image']; ?>" alt="<? echo $news['shortstory']; ?>" width="192" height="108" /></td> </tr> <tr> <td colspan="2"><i><br /> Posted by <? echo $news['author']; ?> on <? echo $news['date']; ?></i></td> </tr> </table><br /> <?php } while ($news = mysql_fetch_assoc($result)); } ?> My php/mysql book doesn't cover pagination so I've been searching the web for a simple pagination script that I can learn from. I got the following one working at http://www.phpsimplicity.com/tips.php?id=1 but it's just showing the next and prev links... no results on the pages and you can click on the next link forever when there's only 11 records in the table I queried. How can I display results on each page and have the info append to the next page? This is the second example I've tried and none seem to explain this part? I need a little help trying to figure this out. I have a page that pulls up data, you can then click on one and go to a page with more detail. On this page you can use the PRrev & Next to go view another detail page on other data. My problem is if my 1st page has 6 sets of data on it but has a total of, say 50, you can only use the Prev & Next to view the 6. I want to be able to use the Prev & Next to go thru all 50. ie Page1 pulls this info data1 data2 data3 data4 data5 data6 < << 1 2 [3] 4 5 6 > >> Page2 Data 1 Lots of info about data 1 < Prev Next > You will only be able to view the 6 data sets in the table above, however there are 50 I want to be able to use the < Prev Next > to go to all of them Can someone help me with this? here is my code Page1 <?php session_start(); // session timing // set timeout period in seconds $inactive = 120; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing include('library/login.php'); login(); mysql_select_db('test'); // sets the sessions for all values $_SESSION=array_merge($_SESSION,$_POST); // echoing to verify $gender=$_SESSION[gender]; $genderPref=$_SESSION[genderPref]; echo "Chossen Gender".$_SESSION['gender']; echo "<br><Br>"; echo "GenderPref".$_SESSION['genderPref']; echo "<br><Br>"; // if the user has been timed out or not logged in if (!isset($_SESSION['clientID'])){ echo "You are not a register user - set this to a simple search form"; echo "<br><a href='form.php'>Form</a>"; } // user is logged in else { $clientID = $_SESSION['clientID']; $sql="SELECT * FROM user WHERE userID='$clientID'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // verifies billing if ($exp_date >= $todays_date) { // billing is up to date $result = mysql_query("SELECT * FROM user WHERE gender='$gender'") or die(mysql_error()); // ------ Sets the display of data ------ $num_rows = mysql_num_rows($result); // number of rows to show per page $rowsperpage = 8; // find out total pages $totalpages = ceil($num_rows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; $result = mysql_query("SELECT * FROM user WHERE gender='$gender' LIMIT $offset, $rowsperpage")or die(mysql_error()); $num_rows = mysql_num_rows($result); if ($num_rows == 0){ echo "<div id='noResults'><span class='sorry'>Sorry</span>, no results found. <br> Please try again with broader search options.</div>"; } else { // format for search results $cells_wide = 2; echo " <table cellspacing='0' cellpadding='3' border='0' width='700'><tr> "; $c = 0; while ($r=mysql_fetch_array($result)) { $userID=$r["userID"]; $gender=$r["gender"]; $aUserIDs[] = $userID; if (0 < $c && 0 == $c % $cells_wide){ echo " </tr><tr> "; } echo " <td width=175> "; echo "<a href='profileSession.php?userID=$r[userID]'>$userID</a>, $gender</td>"; $c++; } // end of while echo " </tr>"; echo " </table> "; } // -------- BUILD THE PAGINATION LINKS -------------------------------- $_SESSION['userID']=$aUserIDs; $_SESSION['userID2']=$aUserIDs2; echo "<div id='navigation'>"; // range of num links to show $range = 3; // if not on page 1, show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>‹‹ </a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'> ‹ </a> "; } // END if ($currentpage > 1) // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($totalpages == 1) { echo ""; } else{ if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } // END if ($x == $currentpage) else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>$x</a> "; } // END else } // END else } // END if (($x > 0) && ($x <= $totalpages)) } // END for loop // if not on last page, show forward and last page links if ($totalpages == 0) { echo ""; } else{ if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'> › </a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2'>›› </a> "; } // END if ($currentpage != $totalpages) }// END else echo "<br>currentpage=$currentpage&gender=$genderPref&genderPref=$gender&ageMin=$ageMin&ageMax=$ageMax&year1=$year1&year2=$year2"; $link='currentpage='; $link1='&gender='; $link2='&genderPref='; $link3='&ageMin='; $link4='&ageMax='; $link5='&year1='; $link6='&year2='; $total=$link.$currentpage.$link1.$genderPref.$link2.$gender.$link3.$ageMin.$link4.$ageMax.$link5.$year1.$link6.$year2; $_SESSION['pages']=$total; echo "<br>$total"; // -------- END PAGINATION -------------------------------------------- } // END if ($exp_date >= $todays_date) else { // billing has expired echo "Billing has expired<br>"; echo $_SESSION['clientID']; echo "<br><a href='session2.php'>Sesssion2</a>"; echo "<br><a href='form.php'>Form</a>"; } } // END valid session ?> Page2 <?php session_start(); // start up your PHP session! include('library/login.php'); login(); mysql_select_db('test'); $userID=$_GET["userID"]; $link=$_SESSION['pages']; // Sends back to display page echo "<a href='searchSession.php?$link' title='Back to Search'>Back to Search</a> "; // sets the Prev & Next $aUsers = isset($_SESSION['userID']) ? $_SESSION['userID'] : array(); $current = $userID; // Ok our current. $iCurKey = array_search($current, $aUsers); $prev = null; $next = null; if ($iCurKey !== false){ $prev = $iCurKey >= 1 ? $aUsers[$iCurKey - 1] : null; $next = $iCurKey < count($aUsers) - 1 ? $aUsers[$iCurKey + 1] : null; } // Lets do this simple. if ($prev !== null){ echo ' <A href="?userID=' . $prev . '">« Previous</A> '; } else{ echo " <span class='empty'>« Previous</span> "; } if ($next !== null){ echo '<A class=right href="?userID=' . $next . '">Next »</A> '; } else{ echo "<span class='empty'> Next »</span>"; } // END of the Prev & Next $result = mysql_query("SELECT userID, first_name, gender FROM user WHERE userID='$userID'") or die(mysql_error()); while ($r=mysql_fetch_array($result)){ $userID=$r["userID"]; $first_name=$r["first_name"]; $gender=$r["gender"]; } echo "<br>$userID, $first_name, $gender"; ?> |