PHP - Insert Query Results In Just A Blank Page
Code: [Select]
The form below is meant to retrieve the named attribute of a form input called "limitedtextfield" , along side the current date and store those values in a database. The form contains some javascript which can be disregarded for this particular problem. [code] <form name="mymind" style= "position:relative;left:40px;" action="insert_status.php" method="post"> <input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,55);" onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,55);" maxlength="55"><br> <font size="1">(Maximum characters: 55)<br> You have <input readonly type="text" name="countdown" size="3" value="55"> characters left.</font> <input type="hidden" name="submitted" value="TRUE"/> <input style="position:relative;left:0px;bottom:0px;" type="submit" name="submit" value="Submit!" /> </form> Here is the php script that processes the form. What it is meant to do is search the database and if no record is found for the authenticated member, input the relevant values into the database. If a record is found, it should update the record. Well every time I hit the submit button, all I get is a blank page. Any clue as to what is going wrong? PS: I checked the database and no values got inserted. Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user require('auth.php'); //Connect to database require ('config.php'); if (isset($_POST['submitted'])) { $query = "SELECT* FROM publications WHERE member_id ='".$_SESSION['id']."' AND cartegory='status'"; $result = @mysql_query($query); $num = @mysql_num_rows($result); if ($num> 0) { $update = mysql_query("UPDATE publications SET publication = '{$_POST['limitedtextfield']}' WHERE member_id = '".$_SESSION['id']."' AND cartegory = 'status'"); header("Location: member.php"); } else { $query = "INSERT INTO publications ( member_id, publication, cartegory, pub_date) VALUES ( '{$_SESSION['id']}','{$_POST['limitedtextfield']}', 'status', NOW() )"; header("Location: member.php"); } } ?> Similar TutorialsHello. My query results are only pulling partial values for table entries with a space (Example: AJ Smith only returns AJ and not the full name ). I am sure this is an easy fix and I am just missing something. Thank you. friends whenever i include this coding to my page, everything goes blank. how could i fix this? Code: [Select] $time_count = 7*24*60*60; // count the 7 days Ads will be deleted $match_time = time()-$time_count; $query = "SELECT id FROM classifieds WHERE time<'".$match_time."' ORDER BY RAND() LIMIT 1"; $result = mysql_query($query); while($ad_id = mysql_fetch_array($result)) $delete =$ad_id[0]; mysql_query("DELETE FROM classifieds WHERE id='$delete'"); I'm not looking for code, mostly just some direction, but I'm sure I'll be back as I try to shape the code. Also, I know very little about coding jQuery, Ajax, etc. Here is what I'm looking for: Basketball coach enters a Page that only he (or admin) can see. (I have that part figured out.) Once there, he has a form to fill out with a player's name and other information. I'd rather there not be 12 rows of empty cells. (Coaches will view that as work) I'd rather not have the Page reload on each "Add", but that would be the lesser of two evils. Is there a way to keep a persistent connection so when a coach hits Add, the player gets added to the database, a new empty form shows up, and the player's information shows up below on a roster? Hello all. I'm using this code to go through the database and output certain user-defined numbers Code: [Select] <?php mysql_connect ("pdb1.awardspace.com", "anastasov_db","moscow1945") or die (mysql_error()); mysql_select_db ("anastasov_db"); $term = $_POST['term']; $sql = mysql_query("select * FROM countries WHERE cocode = '$term'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Code: '.$row['cocode']; echo '<br/> Country: '.$row['coname']; echo '<br/><br/>'; } ?> Now how would I go about making a page that appears if the script can't find any results in the database? Thank you in advance 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 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> $params = array(); $sqlFilters = ""; if(isset($filtertown)) { $sqlFilters .= " AND town =:town"; $params["town"] = $filtertown; } if(isset($filterinstagram) && !empty($filterinstagram)) { $sqlFilters .= " AND instagram >=:instagram"; $params["instagram"] = $filterinstagram; } if(isset($filtertwitter) && !empty($filtertwitter)) { $sqlFilters .= " AND twitter >=:twitter"; $params["twitter"] = $filtertwitter; } if(isset($filterfacebook) && !empty($filterfacebook)) { $sqlFilters .= " AND facebook >=:facebook"; $params["facebook"] = $filterfacebook; } if(isset($filterpinterest) && !empty($filterpinterest)) { $sqlFilters .= " AND pinterest >=:pinterest"; $params["pinterest"] = $filterpinterest; } if(isset($filteryoutube) && !empty($filteryoutube)) { $sqlFilters .= " AND youtube >=:youtube"; $params["youtube"] = $filteryoutube; } if (isset($userstatus)) { if ($userstatus == "active") { $sqlFilters .=" AND profilecomplete = 'yes'";} if ($userstatus == "incomplete") { $sqlFilters .=" AND profilecomplete IS NULL";} if ($userstatus == "block") { $sqlFilters .=" AND status = 'block'";} if ($userstatus == "cancel") { $sqlFilters .=" AND status = 'cancel'";} if ($userstatus == "showall") { $sqlFilters .=" AND status IS NULL";} } if (isset($search)) { if (isset($searchfirstname)) { $sqlFilters .= " AND firstname LIKE :searchfirstname"; $params["searchfirstname"] = $searchfirstname; } if (isset($searchsurname)) { $sqlFilters .= " AND surname LIKE :searchsurname"; $params["searchsurname"] = $searchsurname; } } if (isset($sort)) { $sqlStart = "SELECT * FROM users WHERE usertype = 'influencer'"; $sqlEnd = " ORDER BY `$col` $order LIMIT $offset, $rowsPerPage;"; $sql = $sqlStart.$sqlFilters.$sqlEnd; $sqlfiltercount = $sqlStart.$sqlFilters; $result = $pdo->prepare($sql); $result->execute($params); $resultfiltercount = $pdo->prepare($sqlfiltercount); $resultfiltercount->execute($params); $num_users = $result->rowCount(); $num_usersfiltered = $resultfiltercount->rowCount(); } else { $sqlStart = "SELECT * FROM users WHERE usertype = 'influencer'"; $sqlEnd = " LIMIT $offset, $rowsPerPage;"; $sql = $sqlStart.$sqlFilters.$sqlEnd; // sqlfiltercount removes the LIMIT to show ALL users on this userstatus filter $sqlfiltercount = $sqlStart.$sqlFilters; $result = $pdo->prepare($sql); $result->execute($params); $num_users = $result->rowCount(); echo "$sqlfiltercount"; $resultfiltercount = $pdo->query($sqlfiltercount); $num_usersfiltered = $resultfiltercount->rowCount(); } Hi there. I am writing a tool that displays a list of users. The page has pagination, set at 99 per page. This script combines the various filters added by the administrator, but if they select Active, Blocked or a few others, it bypasses that and runs the bottom {} brackets of query. You have the $num_users which is the total on screen at the time, plus the secondary count of TOTAL users in the system. This count is then show by 'users' on the page.
This runs fine on my local machine running php7.2, but on the live 7.2 server, it's showing nothing. No errors. If I comment out the $resultfiltercount lines, the page loads, but of course no count. Why might it be getting upset at that, and why would it not throw errors on screen at me? I have a form that allows my client to update some products. Now the products are simple just basic info and 1 picture. I have set this up so they can edit the products and change the information, having done this many times in the past, but now hit a puzzling block that I am baffled. The client when editing is presented with the form with the information pulled from the database and the form fields loaded with that data ready to edit. The image can either be left alone or they can choose to upload a new image. They are shown the image they currently have stored in the database. The problem I have is EVEN if they decide not to upload an image and change other information, when the submit the form it must be sending a blank value for the image somewhere as it is updating the database and removing the image reference as if it has been removed. I have an if/else statement based on the form to perform 2 different queries for the update in mysql. Here is the code for the form update, as you can see the image should not update?? Please help?? if ($_SERVER['REQUEST_METHOD'] =='POST') { //This stops SQL Injection in POST vars foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } // **************************** THIS IS FOR NO NEW IMAGE ******************************** if ($_SERVER['REQUEST_METHOD'] =='POST' && empty($_FILES['product_image']['name'])) { # setup SQL statement for no new image $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } // **************************** THIS IS FOR A NEW IMAGE ******************************** else { // Check the image type is a jpeg or gif for the image. if (($_FILES['product_image']['type'] != "image/gif") && ($_FILES['product_image']['type'] != "image/jpeg") && ($_FILES['product_image']['type'] != "image/pjpeg")) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">You have chosen not to upload a <b>Product Image</b>.<BR></SPAN>" ; } elseif ($_FILES['product_image']['size'] > 100000) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">The file size is bigger than 300kb.<BR></SPAN>" ; } else { move_uploaded_file($_FILES['product_image']['tmp_name'], "/httpdocs/product_images/".$_FILES['product_image']['name']) ; echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\"><B>Your front image has successfully uploaded.</B><BR></SPAN>" ; } } # setup SQL statement for update $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}', product_image = '{$_FILES['product_image']['name']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } #execute SQL statement $result = mysql_db_query( *****,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } I'm getting this error "Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/westiehi/public_html/groupBOS.php on line 36" for this code: Code: [Select] $query_rs_specialty = "SELECT * FROM specialty WHERE Group_Place <> '' and Date>= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) ORDER BY Date DESC"; I've tried everything to get this to take records where the one field is blank and the date is greater than a date 6 months ago but nothing seems to work. Help would sure be appreciated!! 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 am using Magento (Ver 1.9.x) If i try with my localhost success url like, http://192.168.1.65/magento/index.php/checkout/onepage/success/ and return success message with order id. if i try with live, success url like, https://abc.in/payubiz/redirect/success/ success page like blank page. How to solve the issue? Code : https://github.com/ZusZus/Payubiz Edited February 4, 2020 by aveevaCan someoneplease help, I need to setup an error page like IF Username and Password are wrong then show an error also if there is no username or password in the fields and I just click LOGIN, I get a blank page?! Can someone please help me here or point me to a relevant tutorial? thanks here is my page: http://www.retroandvintage.co.uk/default.php here is my code: Code: [Select] <?php session_start(); include_once("config.php"); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); /* Login script: This script does the following: Checks that the user is NOT already logged in - if they are they are redirected to the members page by the 'checkLoggedIn()' function. Checks if the login form has been submitted - if so, the 'login' and 'password' fields are checked to ensure they are of the correct format and length. If there are any problems here an error is added to the $messages array and then the script executes the 'doIndex()' function - this function basically outputs the main 'index' page for this script - ie the login form. If there are no problems with the previous step, the 'login' and 'password' field data is passed to the 'checkPass' function to check that an entry exists in the 'users' table for that login/password pair. If nothing is returned from the 'checkPass()' function, an error is added to the $messages array and the 'doIndex()' function is called as above. If a row of data is returned from the 'users' table, the data is passed to the 'cleanMemberSession()' function - which initializes session variables and logs the user in. The user is then forwarded to the members page. If the form hasn't yet been submitted, then the 'doIndex()' function is called and the login page is displayed. */ // Check user not logged in already: checkLoggedIn("no"); // Page title: $title="Member Login Page"; // if $submit variable set, login info submitted: if(isset($_POST["submit"])) { // // Check fields were filled in // // login must be between 4 and 15 chars containing alphanumeric chars only: field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 4, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 4, 15); // if there are $messages, errors were found in validating form data // show the index page (where the messages will be displayed): if($messages){ doIndex(); // note we have to explicity 'exit' from the script, otherwise // the lines below will be processed: exit; } // OK if we got this far the form field data was of the right format; // now check the user/pass pair match those stored in the db: /* If checkPass() is successful (ie the login and password are ok), then $row contains an array of data containing the login name and password of the user. If checkPass() is unsuccessful however, $row will simply contain the value 'false' - and so in that case an error message is stored in the $messages array which will be displayed to the user. */ if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { // login/passwd string not correct, create an error message: $messages[]="Incorrect login/password, try again"; } /* If there are error $messages, errors were found in validating form data above. Call the 'doIndex()' function (which displays the login form) and exit. */ if($messages){ doIndex(); exit; } /* If we got to this point, there were no errors - start a session using the info returned from the db: */ cleanMemberSession($row["rsUser"], $row["rsPass"]); // and finally forward user to members page (populating the session id in the URL): header("Location: main.php"); } else { // The login form wasn't filled out yet, display the login form for the user to fill in: doIndex(); } /* This function displays the default 'index' page for this script. This consists of just a simple login form for the user to submit their username and password. */ function doIndex() { /* Import the global $messages array. If any errors were detected above, they will be stored in the $messages array: */ global $messages; /* also import the $title for the page - note you can normally just declare all globals on one line - ie: global $messages, $title; */ global $title; } // drop out of PHP mode to display the plain HTML: ?> <!doctype html> <html> <head> <title>List of Pubs and Bars in the UK</title> <meta name="description" content="Pubs and bars in the UK, nightlife for food and drink" /> <meta name="keywords" content="Pubs, bars, List, uk, nightlife, drinking, drinks, beer, lager, food" /> <meta name="Content-Language" content="en-gb" /> <meta name="robots" content="FOLLOW,INDEX" /> <meta name="revisit-after" content="2 days" /> <meta name="copyright" content="jbiddulph.com" /> <meta name="author" content="John Biddulph - Professional web site design and development in the south of england mainly worthing and brighton" /> <meta name="distribution" content="Global" /> <meta name="resource-type" content="document" /> <link rel="stylesheet" type="text/css" href="css/reset.css" /> <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.6.custom.css" title="default" /> <link rel="alternate stylesheet" type="text/css" href="css/south-street/jquery-ui-1.8.6.custom.css" title="1" /> <link rel="alternate stylesheet" type="text/css" href="css/redmond/jquery-ui-1.8.6.custom.css" title="2" /> <script type="text/javascript" src="js/stylechanger.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script> <script type="text/javascript"> $(function(){ // Accordion $("#accordion").accordion({ header: "h3" }); // Tabs $('#tabs').tabs(); // Dialog $('#dialog').dialog({ autoOpen: false, width: 600, buttons: { "Ok": function() { $(this).dialog("close"); }, "Cancel": function() { $(this).dialog("close"); } } }); // Dialog Link $('#dialog_link').click(function(){ $('#dialog').dialog('open'); return false; }); // Datepicker $('#datepicker').datepicker({ inline: true }); //hover states on the static widgets $('#dialog_link, ul#icons li').hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ); }); </script> <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> </head> <body> <?php if($messages) { displayErrors($messages); }?> <header> <div id="title"> <h1>My Pub Space <a href="#" onClick="setActiveStyleSheet('default'); return false;"><img src="images/0.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('1'); return false;"><img src="images/1.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('2'); return false;"><img src="images/2.gif" width="15" height="15" border="0" alt="css style" /></a> <span> <form method="post" class="textbox" action="search.php"> Town/City: <input type="text" size="26" class="searchbox" value="" name="rsTown" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="images/upArrow.png" style="position: relative; top: -36px; left: 105px; z-index:1;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> <input type="image" src="images/go.png" height="30" with="30" value="GO" /> </form> </span> </h1> </div> </header> <nav> <ul> <li class="selected"><a href="default.php">Home</a></li> <li><a href="#">Pubs</a></li> <li><a href="#">Members</a></li> <li><a href="#">Events</a></li> <li><a href="register.php">Register</a></li> </ul> </nav> <section id="intro"> <header> <h2>Your social guide to going down the pub, online!</h2> </header> <p>Stuck in town with nowhere to go? Not sure if up the road or down the street is best? Need to be somewhere warm, cosy and friendly. Need a drink?....<br />You've come to the right place, mypubspace has it all!</p> <img src="images/pub.jpg" alt="pub" /> </section> <div id="content"> <div id="mainContent"> <section> <article class="blogPost"> <header> <h2>Pubs and Bars UK Listing</h2> </header> <?php $tableName="pubs"; $targetpage = "default.php"; $limit = 20; $query = "SELECT COUNT(*) as num FROM $tableName"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages['num']; $stages = 3; $page = mysql_escape_string($_REQUEST['page']); if( isset($_REQUEST['page']) && ctype_digit($_REQUEST['page']) ) { $page = (int) $_GET['page']; $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM $tableName LIMIT $start, $limit"; $result = mysql_query($query1); // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <div id="accordion"> <?php while($row = mysql_fetch_array($result)) { echo '<div><h3><a href=\"#\">'.$row['rsPubName'].'</a></h3><div>'.$row['rsAddress'].'<br />'.$row['rsTown'].', '.$row['rsCounty'].'<br />'.$row['rsPostCode'].'<br /><br />Region: '.$row['Region'].'<br /><br />Telephone: '.$row['rsTel'].'</div></div>'; } ?> </div> </article> </section> </div> <aside> <section> <header> <h3>Members Login Area</h3> </header> <form method="post" class="textbox" action="<?php print $_SERVER["PHP_SELF"]; ?>"> Username: <br /> <input type="text" class="textbox" name="rsUser" value="<?php print isset($_POST["rsUser"]) ? $_POST["rsUser"] : "" ; ?>"> Password: <br /> <input type="password" class="textbox" name="rsPass"> <br /> <br /> <input name="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="submit" value="Login"> <br /> </form> <ul> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="register.php">Sign up</a></span></button></li> <li><button id="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"><a href="forgot.php">Forgot Password</a></span></button></li> </ul> </section> <section> <header> <h3>Quick Search</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </aside> </div> <footer> <div> <section id="about"> <header> <h3>About</h3> </header> <p>My Pub Space is one of the largest and newest UK Pubs and Bars Listing sites online. It is not just a list of pubs, we have added a touch of interactive social pubbing experience online! Once registered, you can view information on pubs in your area, write reviews, organise your evenings out!</p> </section> <section id="blogroll"> <header> <h3>Links</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> <section id="popular"> <header> <h3>Popular</h3> </header> <ul> <li><a href="#">Coming Soon!</a></li> </ul> </section> </div> </footer> </body> </html> Hello: Did my first post last week and am new to PHP. Making the jump from Classic ASP into PHP. I got some good advice last time. I have a feedback form I have been using, and it works fine for sending results to the website owner. How can I add to it so it will first add all the data to mySQL database, and then email the results to the site owner? Also, I hear about SQL injection attacks a lot - is my current code safe from that? This is what I have: contact.php Code: [Select] ... <form method="post" name="myform" action="sendmail.php"> Full Name: <input type="text" name="FullName" /> Address: <input type="text" name="Address" /> City: <input type="text" name="City" /> State: <input type="text" name="State" /> Zip: <input type="text" name="Zip" /> Phone: <input type="text" name="Phone" /> Email: <input type="text" name="Email" /> Website: <input type="text" name="Website" /> Comments: <textarea cols="43" rows="6" name="Comments"></textarea> <input type="submit" /><br /> </form> ... sendmail.php Code: [Select] <?php $FullName = $_REQUEST['FullName'] ; $Address = $_REQUEST['Address'] ; $City = $_REQUEST['City'] ; $State = $_REQUEST['State'] ; $Zip = $_REQUEST['Zip'] ; $Phone = $_REQUEST['Phone'] ; $Email = $_REQUEST['Email'] ; $Website = $_REQUEST['Website'] ; $Comments = $_REQUEST['Comments'] ; mail( "info@website.com", "Contact Request", "Full Name: $FullName\nAddress: $Address\n City: $City\n State: $State\n Zip: $Zip\n Phone: $Phone\n Email: $Email\n Website: $Website\n Comments: $Comments\n", "From: $Email" ); header( "Location: http://www.website.com/thanks.php" ); ?> Any help or coding examples would be most appreciated! Thanks! 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? 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. 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> "; } ?> I am able to run and display two queries I need for my program but having issues comparing the two result sets. If they are identical, means both tables are also identical (the query is for the table's schemas in MS-SQL) Here's the relevant part ... Code: [Select] //Variables $table_name=$_POST['table_name']; // Connect via Windows authentication $server = 'win1\i01'; //Connection info for PRO $connectionInfoPRO = array( 'Database' => 'adventureworks', 'CharacterSet' => 'UTF-8' ); $dbPRO = sqlsrv_connect($server, $connectionInfoPRO); if ($dbPRO === false) { exitWithSQLError('Database connection to PRO failed'); } //Connection info for ITG $connectionInfoITG = array( 'Database' => 'adventureworksCOPY', 'CharacterSet' => 'UTF-8' ); $dbITG = sqlsrv_connect($server, $connectionInfoITG); if ($dbITG === false) { exitWithSQLError('Database connection to ITG failed'); } /* Set up and execute the query. */ $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'"; // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1); if ($qresult1 === false) { exitWithSQLError('Query of product data failed.'); } echo '<tr><th>NAME</th><th>TYPE</th><th>POSITION</th><th>DEFAULT</th><th>LENGHT</th><th>IS NULLABLE</th></tr>'; // Retrieve individual rows from the result while ($row1 = sqlsrv_fetch_array($qresult1)) { echo '<tr><td>', htmlspecialchars($row1['COLUMN_NAME']), '</td><td>', htmlspecialchars($row1['DATA_TYPE']), '</td><td>', htmlspecialchars($row1['ORDINAL_POSITION']), '</td><td>', htmlspecialchars($row1['COLUMN_DEFAULT']), '</td><td>', htmlspecialchars($row1['CHARACTER_MAXIMUM_LENGTH']), '</td><td>', htmlspecialchars($row1['IS_NULLABLE']), "</td></tr>\n"; } // null == no further rows, false == error if ($row1 === false) { exitWithSQLError('Retrieving schema failed.'); } //Run ITG query $query2 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'"; $qresult2 = sqlsrv_query($dbITG, $query2); if ($qresult2 === false) { exitWithSQLError('Query of product data failed.'); } echo '<tr><th>NAME</th><th>TYPE</th><th>POSITION</th><th>DEFAULT</th><th>LENGHT</th><th>IS NULLABLE</th></tr>'; // Retrieve individual rows from the result while ($row2 = sqlsrv_fetch_array($qresult2)) { echo '<tr><td>', htmlspecialchars($row2['COLUMN_NAME']), '</td><td>', htmlspecialchars($row2['DATA_TYPE']), '</td><td>', htmlspecialchars($row2['ORDINAL_POSITION']), '</td><td>', htmlspecialchars($row2['COLUMN_DEFAULT']), '</td><td>', htmlspecialchars($row2['CHARACTER_MAXIMUM_LENGTH']), '</td><td>', htmlspecialchars($row2['IS_NULLABLE']), "</td></tr>\n"; } // null == no further rows, false == error if ($row2 === false) { exitWithSQLError('Retrieving schema failed.'); } How can I compare $row1 and $row2 here (the query results for each one) and validate if they both have same results, each and all columns. Any help is highly appreciated! this is my query code Code: [Select] <?php $wsi_query = "(SELECT * FROM (SELECT a.no_Yards AS 'yards', a.Day_Swam AS 'date', a.Season AS 'season', (SELECT sum(no_yards) FROM swimming WHERE Season = '$ws') AS 'totalyards', (SELECT AVG(no_Yards) FROM swimming WHERE Season = '$ws') AS 'avg', (SELECT count(*) FROM swimming WHERE Season ='$ws') AS 'timelaps', (SELECT 1 + count(*) FROM swimming b WHERE b.no_Yards > a.no_Yards AND Season = '$ws') AS hrank, (SELECT 1 + count(*) FROM swimming b WHERE b.no_Yards < a.no_Yards AND Season = '$ws') AS lrank FROM swimming AS a) AS x WHERE Season = '$ws' )"; $wsi_result = mysql_query($wsi_query) or die("Query failed ($wsi_query) - " . mysql_error()); $wsi_row = mysql_fetch_assoc($wsi_result); ?> what it should do is output both the min and the max values like this Code: [Select] <?php while ($mm_wsi_row = mysql_fetch_assoc($wsi_result)){ if ($mm_wsi_row['hrank'] == 1){ if ($mm_wsi_row['date'] == "0000-00-00"){$dayswam = "";}else{$dayswam = $mm_wsi_row['date'];} echo "<tr>"; echo "<td style='background-color:#F90'>Max Length:</td>"; echo "<td>" . number_format($mm_wsi_row['yards']) . "</td>"; echo "<td>" . $dayswam . "</td>"; echo "</tr>"; } if($mm_wsi_row['lrank'] == 1){ if ($mm_wsi_row['date'] == "0000-00-00"){$dayswam = "";}else{$dayswam = $mm_wsi_row['date'];} echo"<tr>"; echo "<td style='background-color:#F90'>Min Length:</td>"; echo "<td style='background-color:#FF9'>". number_format($mm_wsi_row['yards']) . "</td>"; echo "<td style='background-color:#FF9'>" . $dayswam . "</td>"; echo "</tr>"; } ?> the problem is that it doesn't work right all the time for some it just shows the min while others it just shows max I've tested the query in MySQL workbench so i know that that is working right but idk why it works right for some and doesn't work for others 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 |