PHP - Where Clause Messing Up Query For Pagination!
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. Similar TutorialsHi, I'm making an attempt to build a small cms based site. I have read in a lot of places it is best to use the id of a table row to fetch contents, but being as I am using url rewrite in frontend, it won't be showing query strings, so I thought I would ask if anyone saw any potential problems if I did the following. Page table looks like this: Pages - id - name - content In backend, the user has a form to name the page and use ckeditor to add rich content. I will use php to ensure that the name is alphanumeric and use strtolower & str_replace to ensure that My First HTML Page is sent to mysql as my-first-html-page and also check that a row with this name does not already exist. So on front end this page url will be mywebsite.com/my-first-html-page So to output the content I strip out the domain & / so I'm left with the name as entered in the db. $url = $_SERVER['REQUEST_URI']; $url = str_replace ('/','',$url); Then in my function to output content I will use WHERE name = $url I have several radio buttons (dynamically generated) and I want to use the selected value in a MySql query WHERE clause. Is it possible? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=342695.0 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 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 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 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. 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'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. Hi. I am building an update table form. In this table there are only two fields, Header and Intro. Now I have the form and currently it displays whats already in the database. Now when the user edits these two fields and presses edit. Obviously I want it to update these fields. I have the code here but there is an issue with it. At the end of the update I believe I need a update fields WHERE....... which would be used if there was more than one entrance in the table but there is and only ever will be one entry. WHERE what? I dont have a where anything. Do I need this or can it be omitted somehow? <?php if(isset($_POST['edit'])){ //Process data for validation $header = trim($_POST['header']); $intro = trim($_POST['intro']); //Perform validations next //Prepare data for db insertion $header = mysql_real_escape_string($header); $intro = mysql_real_escape_string($intro); //insert $qUpdateDetails = "UPDATE index SET `header` = '".$header."', `intro` = '".$intro."', WHERE ???????='".?????????."'"; $rUpdateDetails = mysql_query($qUpdateDetails) or die(mysql_error()); //next page $page_edit = "Index page has been edited"; $url = "signed.php?edit='".$page_edit."'" or die(mysql_error()); header("Location: ".$url."") or die(mysql_error()); exit(); } } ?> Hi
I am now on to viewing listings but want to to show listings that are just submitted by that user and display them on their profile page but can't get the WHERE clause working
Below is the coding for what I have
Profile page
echo "<p><a href='view-private-listings.php?id={$_SESSION['user_id']}'>View Listings</a></p>";Add Listing page HTML Submitted By: <input type="text" name="submittedby">View Listings Page <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php $title = "Private Seller Listings"; include ( 'includes/header.php' ); ?> <?php require_once("functions.php"); $con=mysqli_connect("host","username","password","database"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Start a session for error reporting session_start(); $submittedby=$_POST['submittedby']; $listingtitle=$_POST['listingtitle']; $query = mysqli_query($con,"SELECT listingtitle FROM privatelistings WHERE item LIKE '%$submittedby%'"); echo "<p>Title: {$listingtitle['listingtitle']}</p>"; mysqli_close($con); ?> <?php include( 'includes/footer.php' ); ?>All I get is the following error Notice: Undefined index: listingtitle in /zacs-car-site/view-private-listings.php on line 26 Thank you in advance Kind regards Ian This may be super simple, but it's stumping me. Is this an If/Then clause: Code: [Select] ($month != 1 ? $month - 1 : 12) Is it saying if $month does not equal 1 then $month-1; if so, then what does the colon mean? If not, then what is this piece of code doing? hi, how can I add more than one ID to a WHERE clause? Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1 "; I need to select products with different id's i.e Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1,2,3,4,5 "; Thanks Code: [Select] $search = "`title` LIKE '%Silvin AND wts%'"; I want to search for both of those keywords why not work? Hi, I have an empty array and i populated the array through code and i printed to check if everything ok. So far so good. I now have an array say $ids = ('123','456'). Now, i have a table in db that has ids as well, I need to make a query to check for id's that are not inside the array, so if the db table have '123','456','789' i want the result of the query to be only the last one '789'. $arr = array(); array_push($arr,$previd2); print_r ($arr); I get the result as follows: Array ( [0] => 533349 [1] => 533355 ) so what query i can use to get the other id's from db table that is not part of that array? here is what i tried: $qry = "select staffname, joindate from staff WHERE OracleID NOT IN ($arr)"; $answ = mysqli_query($con, $qry); I get error: Notice : Array to string conversion in C:\xampp\htdocs\AttendanceSystem\login\reportsforallid.php Edited March 30, 2020 by ramiwahdan more info I am brand new to mysql and php but I have created a database and loaded two tables using cPanel and phpMyAdmin. Now I need some programs to access my data. I have a couple of simple ones that work, but I can't figure out what I really need, I am trying to Select a table Where the Value is a $variable, not a fixed value. Of course the end result will be to pass the value from a Form, but I have to get this to work first. <?php // Connect to database============================= include("connect_db.php"); $table='airplanes'; $amano='123456' $iden='1' // Send query =========================================================== // $result = mysql_query("SELECT * FROM {$table} where ama='123456'"); == this works // $result = mysql_query("SELECT * FROM {$table} where ama='940276'"); == this works // $result = mysql_query("SELECT * FROM {$table} where id='1'"); // this works // $result = mysql_query("SELECT * FROM {$table} where id = '{$iden}'"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = ($iden)"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where ama='$amano'"); // == doesnt work $result = mysql_query("SELECT * FROM {$table} where ama=($amano)"); // == doesnt work Thanks Hi, I have a SQL statement: $sql='SELECT PROPID, ADDRESS_1, ADDRESS_2, TOWN, POSTCODE1, POSTCODE2, BEDROOMS, BATHROOMS, RECEPTIONS, PRICE, TRANS_TYPE_ID FROM properties WHERE TRANS_TYPE_ID=2 AND BEDROOMS =3 AND PROP_SUB_ID IN (1,2,3,4,5,6,21,22,23,24,27,30,95,128,131) ORDER BY DATE_ADDED, PROPID DESC'; I want to be able to get the fields and their corresponding values as such: $result['TRANS_TYPE_ID']=2; $result['BEDROOMS']=3; And then capture the values in PROB_SUB_IN IN(*) How can I do this? Any help will be greatly appreciated. Thanks I have this code: Code: [Select] if (isset($_POST['update'])){ $ids = implode(",", array_map('intval', $_POST['m'])); $ranks = implode(",", array_map('intval', $_POST['ranks'])); if ($ids < 1) message("Incorrect Data"); if ($ranks < 0) message("Incorrect Data"); echo $ids; echo "<br>"; echo $ranks; exit; $db->query('UPDATE friends set RANKS WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); redirect("s.php?section=Friends","Thanks, Ranks Updated"); } I grab the id's from the rank This will spit out 3,4 for $ids and for $ranks, 1,2 as you can see, set for 1 and 2 respectivaly. My problem is how can I use MYSQL to update the data correspond to each id using a IN clause? Code: [Select] $db->query('UPDATE friends set RANKS = "LOST $RANKS? HERE" WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); |