PHP - Paging Through Results From Query Based On Form Variables
I'm very new to this and really could use some help. I've got a Web app that has one form that collects data from the user and puts it into a mysql database and has another form that allows the user to select critiera to find records in the database and display them on the page. All this is working just fine, but now that my database is getting more data in it, I want to add functionality to display 10 records on a page with results page navigation links so the user can move forward and backward in the results set. This part is not working and I've put in echo statements to figure out what the code is doing.
The problem I'm having is that when the selection critiera pulls more than 10 records from the database, the first page of results is correct per the selection criteria entered by the user on the select form. When the 'next' link is selected to review the second page of results, the query is executed again. But this time the form variables have been reset and the results now contains the entire contents of the db. The start record is set to look at the 11th instance of the results set, so the second page starts with the 11th record in the database instead of the 11th record in the original results set. The original select statement is built by determining which criteria is selected using $_POST against each form variable. How can I retain the form variables or the original select statement so the second execution of the select statement results in the same results set as the first? The other option that may be better is to retain the original results set and avoid re-executing the select statement altogether. But I don't know how to do that either. Any suggestions, code samples or adivice is much appreciated! Similar TutorialsHello, I am trying to get a page that shows a list of parts, with their quantities, condition and type. So parts that are identical are counted as 2, 3 etc if they are the same part, condition and type. But if one or more parts of the same type has any one of those variables different to the rest, it/they need to come out on a new line with the correct quantity against them. I have tried using arrays and I can get the quantities working against each part but don't know how to adapt it to achieve what I want. Here is what I have so far: // GET ALL THE PARTS FROM THIS **ONE SUPPLIER** AND FIND OUT THE QUANTITIES... include("../dbconnectlocal.php") ; $result = mysql_query("SELECT supplier, partNumber, newUsed, jobType, directIndirect, currency, vat, total FROM pourbaskets WHERE enquiryRef = '$enqId' AND supplier = '$sSup' ORDER BY partNumber DESC")or die(mysql_error()) ; $quantity = 0 ; $currentCount = 1 ; $partQuantityArray = array() ; // The box for our parts against their quantities. $partsBag = array() ; // For finding out how many unique parts there are later. $partCount = mysql_num_rows($result) ; // How many parts in total. while($row = mysql_fetch_assoc($result)) { // While we are going through each part found... $part = $row['partNumber'] ; $cond = $row['newUsed'] ; $jtyp = $row['jobType'] ; $curr = $row['currency'] ; $vat = $row['vat'] ; $tota = $row['total'] ; array_push($partsBag, $part) ; if($partCount == 1) { // Just one part... $quantity = 1 ; array_push($partQuantityArray, $part, $quantity) ; } if(!$prevItem && $partCount != 1 { // Is the first item and not the only one... $prevItem = $part ; // Set it to be the previous... $quantity++ ; // Increase quantity (to 1 now)... } elseif($currentCount == $partCount && $partCount != 1) { // If it's the last one in the list and not the only one... if($prevItem != $part) { array_push($partQuantityArray, $prevItem, $quantity) ; $quantity = 1 ; array_push($partQuantityArray, $part, $quantity) ; //$prevItem = $part ; } elseif($prevItem == $part) { // The final part is the same as the last one... $quantity++ ; array_push($partQuantityArray, $part, $quantity) ; } else { array_push($partQuantityArray, $part, $quantity) ; } } elseif($prevItem == $part) { // If the current item is the same as the last item... $quantity++ ; // Increase quantity... } elseif($partCount != 1) { // If it's a new item and not the only one, store the quantity of the last item, and start at 1... array_push($partQuantityArray, $prevItem, $quantity) ; $quantity = 1 ; $prevItem = $part ; } $currentCount++ ; } print_r($partQuantityArray) ;exit(); //////////////////// END OF QUANTITY FINDER ////////////////////////////// I have attached what I would like it to come out as. Hi. I'm trying to make a sort of a forum, and this is the part of the code that needs to be changed, only I don't know how. Code: [Select] mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name ORDER BY id DESC"; // OREDER BY id DESC is order result by descending $result=mysql_query($sql); ?> <table width='50%' border="0" align="center" cellpadding="3" cellspacing="1"> <?php $limit=10; $page=0; $numrows = mysql_num_rows($result); $pages = intval($numrows/$limit); if ($numrows % $limit) { $pages++;} $current = ($page/$limit) + 1; if (($pages < 1) || ($pages == 0)) { $total = 1;} else { $total = $pages;} $result = mysql_query("SELECT * FROM $tbl_name ORDER BY id DESC LIMIT $page,$limit"); while($rows=mysql_fetch_array($result)){?> <tr><td><font size="+2"><a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a><BR></font></td> <td width='0*'><? echo $rows['datetime']; ?></td></tr> <tr><td><? echo substr($rows['detail'], 0, 250)."..."; ?> <a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo "Citeste mai mult";} ?></a> </td></tr> <tr><tr><td> <? if ($page != 0) { // Don't show back link if current page is first page. $back_page = $page - $limit; echo("<a href=\"$PHP_SELF?query=$query&page=$back_page&limit=$limit\">back</a> \n");} for ($i=1; $i <= $pages; $i++) // loop through each page and give link to it. { $ppage = $limit*($i - 1); if ($ppage == $page){ echo("<b>$i</b>\n");} // If current page don't give link, just text. else{ echo("<a href=\"$PHP_SELF?query=$query&page=$ppage&limit=$limit\">$i</a> \n");} } if (!((($page+$limit) / $limit) >= $pages) && $pages != 1) { // If last page don't give next link. $next_page = $page + $limit; echo(" <a href=\"$PHP_SELF?query=$query&page=$next_page&limit=$limit\">next</a>");} ?> </td></tr></tr><?php mysql_close(); ?> </table> I made a database with 4 fields and 11 entries. The script shows the last 10 entries just as it should, but when I click on the 'next' button, nothing happens (it should show the first entry, but it just refreshes the page, and still the last 10 entries/1st page are shown). I think it has something to do with the link, but I can't figure out what exactly. Can someone help, or at least give me a hint? Thanks in advance. Bye. 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 What would be the correct way to close a mysql query? At current the second query below returns results from the 1st query AND the 2nd query The 3rd query returns results from the 1st, 2nd and 3rd query. etc etc. At the moment I get somthing returned along the lines of... QUERY 1 RESULTS Accommodation 1 Accommodation 2 Accommodation 3 QUERY 2 RESULTS Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 QUERY 3 RESULTS Takeaways 1 Takeaways 2 Takeaways 3 Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php include($_SERVER['DOCUMENT_ROOT'].'/include/db.php'); ?> <title>Untitled Document</title> <style type="text/css"> <!-- --> </style> <link href="a.css" rel="stylesheet" type="text/css" /> </head><body> <div id="listhold"> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Placestostay.html">Places To Stay</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Accommodation' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingout.html">Eating Out</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingin.html">Eating In</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Takeaways' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------SKILLED TRADES BELOW---------------------------------------------------> <div class="list"><a href="Skilledtrades.html">Skilled Trades</a><br/> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Skilled Trades' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> I'm trying to pull results from a database based on where the user is located based upon the variables $usr_lat & $usr_lng, and search for by a radius of x amount of miles/km (need to make it optional). I can't seem to find exactly what I'm looking for on google so I thought I'd asked here. Any help would be appreciated.
Hi Guys. Hopefully someone can help me with this...New to coding and pretty lost on this. I have a Mysql database which is displaying results to my webpage with no problems. However I would like to be able to add a combo box to my webpage that would update the mysql database results based on the combo box selection. For example if Ford is chosen from the combo box, the webpage would refresh and show all the results for Ford in the webpage. Can someone please help me? Here is the code I have at the moment that works just fine. But results of the database are based on the WHERE statement. Quote <?php $con = mysql_connect("server","database","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("a5525005_cars", $con); $result = mysql_query("SELECT * FROM `cars` WHERE Makel='Ford'"); echo "<table class='ex1' border='0' width='113%' style=text-align:center; cellpadding='6' cellspacing='0'> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr style=font-family:verdana;font-size:80%;>"; echo "<td width=13%>" . $row[""] . "<img src=\"" . $row["Photo"] . "\"></a>"; echo '<td width="14%"><a class="mylink" href="' . $row['URL'] . '">' . $row['Model'] . '</a></td>'; echo '<td width="5%"><a class="mylink" href="' . $row['URL'] . '">' . $row['Year'] . '</a></td>'; echo '<td width="4%"><a class="mylink" href="' . $row['URL'] . '">' . $row['Fuel'] . '</a></td>'; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> How can i put returned values from an sql query, into variables. If the returned values from a query were; email1@com, email2@com, email3@com how would i go about puting them into variables? $value1 = (1st returned value from my sql query, in this case it would be email1@com) $value2 = (2nd returned value from my sql query, in this case it would be email2@com) $value3 = (3rd returned value from my sql query, in this case it would be email3@com) $code = $_GET['postcode']; $message = $_GET['message']; $emailad = "email@email.comuk"; $shortcode = substr($code,0,2); $result = mysql_query("SELECT email FROM treesurgeons WHERE postcode like '%" . $shortcode . "%' ORDER BY companyName LIMIT 3") or die(mysql_error()); echo "<h2>Business Names:</h2>"; while ($row = mysql_fetch_array( $result )) { $message .= "\r\n". $row['email'] ; } echo nl2br ($message); mail( "$emailad", "Header","$message" ); echo "<br>" . "Thank you for using our mail form."; ?> </body> </html> Thankyou for any ideas, or suggestions. hi I have 2 tables (members & friendship) Members table columns: -------------------------------------------- username | password | email | etc .... -------------------------------------------- Person 1 xxxxxx x@x.com person 2 yyyyyy y@y.com Friendship columns: --------------------------------------- username | friend | status | --------------------------------------- person 1 person 2 friends person 2 person 1 friends person 1 person 3 pending I want to query the friendship table: "SELECT friend FROM friendship WHERE username ='$_SESSION['myusername'];' AND status='friends' " (so its basically getting the user names of anyone who is the logged in users friend) And then use the returned user names to select their data from the members table. Any help much appreciated! ^.^ Hello im receiving the error code, Quote Parse error: syntax error, unexpected ';'on line 58 Code: [Select] <?php mysql_connect("","business",""); mysql_select_db("business") or die("Unable to select database"); $result = mysql_query("SELECT subtype FROM business WHERE type ='restaurant' ORDER BY name"); $number_of_results = mysql_num_rows($result); $results_counter = 0; if ($number_of_results != 0) {while ($array = mysql_fetch_array($result);) //THIS IS LINE 58 IN MY CODE $results_counter++; if ($results_counter >= $number_of_results); ?> Firstly do you know why I would get this error? and secondly how do i call my results. I basically want to return my results and then later on format them into lists. I would also like each result to have a different variable name. eg. result1 = $result1 result 2 = $result2 result3 = $result3 etc. any guidance much appreciated. Im a bit lost. I have a search form that has a drop down Code: [Select] <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> I'm trying to limit the results in a foreach loop within what was selected. Meaning, if someone selects 10, results within 10 miles will show The foreach is Code: [Select] foreach ($stores as $k=>$v) { $output = "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['MktName']."</b><br>(approx ".$v." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'>".$storeinfo[$k]['LocAddSt']."<br>"; $output .= $storeinfo[$k]['LocAddCity'].", ".$storeinfo[$k]['LocAddState']." ".$storeinfo[$k]['zipcode']."</p>"; print_r($output); } $v being the distance. So I need to show only the results of $v that are less than $r. How would I go about doing this? Right now, $v displays numbers like 5.04, 173.9 and so forth. Can anybody help me out? Thanks in advance. I would like to create variables based on data stored in a database using the text in the variable. This is so that users using my script can simply add custom settings to the database and automatically use them. Example as follows: Table Structu id, name, value, group The name would become the variable name while the value would become the value of that name. Example row: 1, site_title, testing this out, site_settings Result: $site_title = "testing this out"; I know I will need to use a while() to pull the data but I don't know how to get php to automatically create a variable with the right name/data combo... Any ideas out help. $username = $_POST['uid']; $email = $_POST['mail']; $password = $_POST['pwd']; $passwordRepeat = $_POST['pwd-repeat']; $date = $_POST['date2']; $stream = $_POST['relationship']; $sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);"; $sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);"; $sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);"; mysqli_query($sql1, $conn); mysqli_query($sql2, $conn); mysqli_query($sql3, $conn); $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql2)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='nursing'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql3)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='doctoral'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { $hashedPwd = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream); mysqli_stmt_execute($stmt); header("Location: ../signup.php?signup=success"); exit(); I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed. So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1' But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is. Is this the wrong way to go here? Did I completely mess up the logic? Not sure why this isnt working. Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <LINK REL=StyleSheet HREF="inc/dyn_style.css" TYPE="text/css" MEDIA=screen /> <?php ?> <?php include('logic.inc'); mysqlConnect(); ?> <script type="text/javascript" src="bbeditor/ed.js"></script> <link rel="stylesheet" type="text/css" href="dyn_style.css" /> <title> Social </title> <script type="text/javascript"> function changeTitle(title) { document.title = title; } </script> </head> <body> <?php $inc = 'new_story.php'; $view = 'Newest '; $by = 'added'; $where = " "; $where2 = " "; $order = "ASC"; $gen = "All"; $rat = 'All'; $blerg = ""; $sort = 'newest'; //---------------------------------------------------------------------- if(isset($_GET['sub'])) { $sort = $_GET['sort']; switch($sort) { case "Most Popular"; $by = 'views'; $view = 'Most Popular '; $order = 'DESC'; break; case "Most Reviewed"; $view= 'Most Reviewed '; $by = 'reviews'; $order = 'DESC'; break; case "Newest"; $by = 'added'; $view = 'Newest'; $order = 'ASC'; break; } $genre = mysql_real_escape_string($_GET['cat']); $rating = mysql_real_escape_string($_GET['rat']); if($gen == 'All') { $where = " "; $blerg = ""; } else { $where = "WHERE cat='$gen'"; } if ($rat == "All") { $where2 = ' '; $blerg = 'AND'; } else { $where2 = $blerg ." rating = '$rat' "; } } //---------------------------------------------------------------------- ?> <?php serch(); ?> <form action="story.php" method="get"> <label id='inline'> Order By: </label> <select name='sort'> <option selected='yes' label='Currently Selected' > <?php echo $view; ?> </option> <option> Newest </option> <option> Most Popular</option> <option> Most Reviewed </option> </select> <input type='hidden' value='spec_view' name='p' /> <label id='inline'> Genre/Catagory: </label> <select name='gen'> <option selected='yes' label = 'Selected Genre - <?php echo $gen; ?>'> <?php echo $gen; ?> </option> <option> All </option> <option> Fantasy </option> <option> Adventure </option> <option> Science Fiction</option> <option> Drama</option> <option> Fable </option> <option> Horror</option> <option> Humor</option> <option> Realistic Fiction </option> <option> Tall Tale</option> <option> Mystery </option> <option> Mythology </option> <option> Poetry </option> <option> Shorty Story </option> <option> Romance </option> </select> <label id='inline'> Rating: </label> <select name='rat'> <option selected='yes' label = "Selected Genre - <?php echo $rat; ?>"> <?php echo $gen; ?> </option> <option> All </option> <option> C </option> <option> C13 </option> <option> YA </option> <option> A </option> </select> <input type='submit' value='Go!' name = 'go' /> </form> <?php $query = " SELECT * FROM story_info ORDER BY $by $order $where $where2 "; echo $query; $select = mysql_query($query) or die(mysql_error()); while($rows = mysql_fetch_assoc($select)) { $viewsdb = $rows['views']; $titledb = $rows['title']; $userdb = $rows['user']; $catdb = $rows['cat']; $ratdb = $rows['rating']; $id_db = $rows['story_id']; $sumdb = shorten($rows['sum']); echo "<h3><a href='?p=page&id=$id_db'> $titledb </a> </h3>"; echo "<div id='fun_info'>"; echo "$sumdb <br />"; echo "By <a href='?p=profile&user=$userdb'> $userdb </a> <br /> "; echo "$viewsdb Views | Rated: $ratdb | Catagory: <a href='?p=cat_view&gen=$catdb'> $catdb </a> </div>"; } ?> </div> </body> </html> Can someone please give me some ideas as to what might be wrong with this query...I keep getting no result and am echoing $count for debugging (and usernames and passwords) but get nothing for $count (expecting a 0 or a 1) or $dbusername or $dbpassword $sql="SELECT * FROM `users` WHERE `User name` = '$fusername' and `Password` = '$fpassword'"; $result=mysql_query($sql); $dbusername=mysql_result($result,0,"User name"); $dbpassword=mysql_result($result,0,"Password"); echo $dbusername; echo $dbpassword; // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $fusername and $fpassword, table row must be 1 row echo $fusername; echo $fpassword; echo $count; if($count==1){ (This is where I keep going to the else) quick question, I have this code that returns over 100 buttons: Code: [Select] <?php // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM products"); while($row = mysql_fetch_array($sql)){ $product = $row["product"]; $id =$row["id"]; $price =$row["price"]; ?> <div id="products"> <form action="" method="POST" name="myform<?php echo $id; ?>" class="myform<?php echo $id; ?>"> <input type="hidden" name="hiddenField" class="hiddenField" value="<?php echo $product; ?>" /> <input type="hidden" name="hiddenField2" class="hiddenField2" value="<?php echo $id; ?>" /> <input type="hidden" name="hiddenField1" class="hiddenField1" value="<?php echo $price; ?>" /> <input type="submit" name="submit" class="submit" value="<?php echo $product; ?>" style="background-color:lightgreen; height:50px; width:100px;"> </form> </div> <?php } ?> What I would like is for the buttons to form columns of nine. ie 9 buttons in a column then a new column form.... how do I do this? Hi all, I'm new to php and I was trying to send the results of one query to another query. I need the results of both queries. Here are the queries $cui1 = mysql_query("SELECT DISTINCT CUI FROM MRSTY WHERE STY='ABC' "); $cui2 = mysql_query("SELECT DISTINCT CUI FROM MRSTY WHERE STY='XYZ' "); I want to know if this is possible $cuis = mysql_query("SELECT CUI1,CUI2,REL FROM MRREL WHERE CUI1 IN $cui1 OR CUI1 IN $cui2 "); Thanks. Below is my query which works fine: $query = " SELECT st.CourseId, c.CourseName, st.Year, st.StudentUsername, st.StudentForename, st.StudentSurname, s.ModuleId, m.ModuleName, m.Credits, s.SessionId, s.SessionWeight, gr.Mark, gr.Grade FROM Course c INNER JOIN Student st ON c.CourseId = st.CourseId JOIN Grade_Report gr ON st.StudentId = gr.StudentId JOIN Session s ON gr.SessionId = s.SessionId JOIN Module m ON s.ModuleId = m.ModuleId WHERE (st.StudentUsername = '".mysql_real_escape_string($studentid)."') "; Below is my results outputted by using php: Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAB 72 (A) Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2513 - Systems Strategy Session: AAD 61 (B) Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAE 67 (B) How do I display it using php so that it only shows Course details and Student details only once, it will show each module in the course only once and shows each session being below each module it belongs to: The output from above should look like this in other words: Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAB 72 (A) Session: AAE 67 (B) Module: CHI2513 - Systems Strategy Session: AAD 61 (B) PHP code to output the results: $output1 = ""; while ($row = mysql_fetch_array($result)) { //$result is the query $output1 .= " <p><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Year:</strong> {$row['Year']}<br/> <strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']}) </p>"; $output1 .= " <p><strong>Module:</strong> {$row['ModuleId']} - {$row['ModuleName']} <br/> <strong>Session:</strong> {$row['SessionId']} {$row['Mark']} ({$row['Grade']}) </p>"; } echo $output1; Thank You I was just wondering if this is a way that you can exclude certain rows from a MySQL query. For example if I have 10 records each with a unique id, is there anyway I can get all of the records except record 5? Thanks for any help. Hi I have a query where it returns a few fields based on the location. I created a class for the function and an index page. It does not return any values. Can someone please advise/ THE CLASS Code: [Select] <?php /**************************************** * * WIP Progress Class * * ****************************************/ class CHWIPProgress { var $conn; // Constructor, connect to the database public function __construct() { require_once "/var/www/reporting/settings.php"; define("DAY", 86400); if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error()); if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error()); } public function ListWIPOnLocation($location) { $sql = "SELECT `ProgressPoint.PPDescription` AS Description ,`Bundle.WorksOrder` AS WorksOrder, `Bundle.BundleNumber` AS Number, `Bundle.BundleReference` AS Reference,`TWOrder.DueDate` AS Duedate FROM `TWOrder`,`Bundle`,`ProgressPoint` WHERE `Bundle.CurrentProgressPoint`=`ProgressPoint.PPNumber` AND `TWOrder.Colour=Bundle.Colour` AND `TWOrder.Size=Bundle.Size` AND `TWOrder.WorksOrderNumber`=`Bundle.WorksOrder` AND `ProgressPoint.PPDescription` LIKE '" . $location . "%' ORDER BY TWOrder.DueDate DESC"; mysql_select_db(DB_DATABASE_NAME, $this->conn); $result = mysql_query($sql, $this->conn); echo $sql; while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $return[] = $row; } return $return; } } ?> The index page Code: [Select] <?php // First of all initialise the user and check for permissions require_once "/var/www/users/user.php"; $user = new CHUser(7); // Initialise the template require_once "/var/www/template/template.php"; $template = new CHTemplate(); // And create a cid object require_once "/var/www/WIPProgress/DisplayWIPOnLocation.php"; $WIPProgress= new CHWIPProgress(); $content = "Check WIP Status on Location <br>"; $content = "<form action='index.php' method='get' name ='location'> <select id='location' > <option>Skin Room</option> <option>Clicking</option> <option>Kettering</option> <option>Closing</option> <option>Rushden</option> <option>Assembly</option> <option>Lasting</option> <option>Making</option> <option>Finishing</option> <option>Shoe Room</option> </select> <input type='submit' /> </form>"; $wip = $WIPProgress->ListWIPOnLocation($_GET['location']); // Now show the details $content .= "<h2>Detail</h2> <table> <tr> <th>PPDescription</th> <th>Works Order</th> <th>Bundle Number</th> <th>Bundle Reference</th> <th>Due Date</th> </tr>"; foreach($wip as $x) { $content .= "<tr> <td>" . $x['Description'] . "</td> <td>" . $x['WorksOrder'] . "</td> <td>" . $x['Number'] . "</td> <td>" . $x['Reference'] . "</td> <td>" . $x['DueDate'] . "</td> </tr>"; } $template->SetTag("content", $content); echo $template->Display(); ?> thank you Hello all, I have made the multi level marketing downline tree, but the problem with it now, it gives only the downline of one result, as the query gives 2 results what I want now is to make it give the downline of both results not just one, and it's always 2 results, not more here is my code Code: [Select] <?php $id = $_GET['id']; $result = mysql_query("SELECT id FROM users WHERE id = '".$id."' ORDER BY id"); $row = mysql_fetch_assoc($result); if ($row['id'] == 0) { echo" <table> <div id=\".piccenter\""; echo "<tr>"; echo "<img src=\"icon.gif\" border=0 align=\"center\">"; echo ""; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$row['id']."'"; echo ""; echo "</div>"; } } $result2 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$row['id']."'"); $rows2 = mysql_fetch_assoc($result2); foreach ($rows2 as $row2) { if ($row2['id'] == 0) { echo" <div id=\".picleft\"> <img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0 >"; echo "<br />"; echo "'".$row2['id']."'"; echo "</div>"; echo " <td>"; echo "</td> "; } } $result3 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows2['id']."'"); $row3 = mysql_fetch_assoc($result3); if ($row3['id'] == 0) { echo"<div id=\".picright\"> <img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$row3['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result4 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$row3['id']."'"); $rows4 = mysql_fetch_assoc($result4); if ($rows4['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows4['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result5 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows4['id']."'"); $rows5 = mysql_fetch_assoc($result5); if ($rows5['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows5['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result6 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows5['id']."'"); $rows6 = mysql_fetch_assoc($result6); if ($rows6['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows6['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result7 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows6['id']."'"); $rows7 = mysql_fetch_assoc($result7); if ($rows7['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows7['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result8 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows7['id']."'"); $rows8 = mysql_fetch_assoc($result8); if ($rows8['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows8['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result9 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows8['id']."'"); $rows9 = mysql_fetch_assoc($result9); if ($rows9['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows9['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> </tbody> </table> "; } ?> |