PHP - Question About Breaking Up Mysql Results
Hi all,
In order to teach myself php I am developing a simple cms system to display my graphic design work. Basically I am working on developing a simple portfolio website powered by a custom made CMS. So far, I can create new posts which are being stored in a MySQL db. My index page runs a sql query to get the latest posts and sorts them by category. Currently the results look like this: Quote Title1 Category A Text Title2 Category A Text Title3 Category B Text Title4 Category B Text The code to generate this looks like this: $content = mysql_query("SELECT * FROM posts ORDER BY category, date DESC"); while($row = mysql_fetch_array($content)) { echo '<h2 class="post_title">'.$row['title'].'</a></h2>'; echo '<p class="cat">category: '.$row['category'].'</p>'; echo '<p class="post_body">'.$row['body'].'</p>'; echo '<p class="image">image: '.$row['image'].'</p>'; echo '<p class="lowerlefttext_metainfo">by <span class="lowerlefttext_author">'.$row['author'].'</span> on '.$row['date'].'</p>'; } What I would like however is this: Category A Title 1 Text Title 2 Text Category B Title 3 Text Title4 Text I am not sure how to do this elegantly without having to code an sql query per category, which I don't think is efficient? Thank you! Similar TutorialsHey all I'm working on an auction website. I've added a new column to the 'Auctions' table, however the 'sell.php' page now does not work with this new column (I've deleted the column and tested again and it works, so that's definitely the cause). The new column can not be in a separate table as it needs to pull 'id' values from the 'Auctions' table for various functions. My question to you is, is there any PHP snippet I can use to tell sell.php to stop reading the 'Auctions' table once it reaches the column I've added? The new column is called 'shipped' if that's of any relevance. Below is some of the PHP I'm working on on the sell.php page. #//Populate arrays $UPLOADED_PICTURES[] = $file; $UPLOADED_PICTURES_SIZE[] = filesize($image_upload_path.session_id()."/".$file); } } } $_SESSION["UPLOADED_PICTURES"] = $UPLOADED_PICTURES; $_SESSION["UPLOADED_PICTURES_SIZE"] = $UPLOADED_PICTURES_SIZE; $_SESSION["GALLERY_UPDATED"]=true; if($sessionVars['SELL_action']=='edit') { $sessionVars["OLD_GALLERYFEE"] = $SETTINGS["picturesgalleryvalue"] * count($UPLOADED_PICTURES); } else { $sessionVars["OLD_GALLERYFEE"] = 0; } } } } $with_reserve = $sessionVars["SELL_with_reserve"]; $reserve_price = $sessionVars["SELL_reserve_price"]; $minimum_bid = $sessionVars["SELL_minimum_bid"]; $duration_hours = $sessionVars["SELL_duration_hours"]; $duration_minutes = $sessionVars["SELL_duration_minutes"]; $pict_url=$sessionVars["SELL_pict_url"]; $imgtype = $sessionVars["SELL_file_uploaded"]; $title = $sessionVars["SELL_title"]; $description = stripslashes($sessionVars["SELL_description"]); $pict_url = $sessionVars["SELL_pict_url"]; $atype = $sessionVars["SELL_atype"]; $adultonly = $sessionVars["SELL_adultonly"]; $TPL_item_value = $item_value = $sessionVars["SELL_item_value"]; $TPL_number_of_bids =$number_of_bids=$sessionVars["SELL_number_of_bids"]; $TPL_bid_value = $bid_value = $sessionVars["SELL_bid_value"]; $iquantity = $sessionVars["SELL_iquantity"]; $buy_now = $sessionVars["SELL_with_buy_now"]; $buy_now_price = $sessionVars["SELL_buy_now_price"]; $duration = $sessionVars["SELL_duration"]; $duration_second = $sessionVars["SELL_duration_second"]; $minimum_users = $sessionVars["SELL_minimum_users"]; $relist = $sessionVars["SELL_relist"]; $increments = $sessionVars["SELL_increments"]; $customincrement = $sessionVars["SELL_customincrement"]; $international = ($sessionVars["SELL_international"])?"on":""; $sellcat = $_SESSION['sellcat']; $private = $sessionVars["SELL_private"]; if($private != 'y') $private = 'n'; $sendemail = $sessionVars["SELL_sendemail"]; $txt = $sessionVars["SELL_txt"]; $num = $sessionVars["SELL_num"]; $buy_now_only = $sessionVars["SELL_buy_now_only"]; and... $auction_id=$sessionVars['SELL_auction_id']; } elseif ($sessionVars["SELL_action"] == "reopen") { $query = "UPDATE BPLA_auctions set title = '".addslashes($sessionVars["SELL_title"])."', starts = '".$a_starts."', starts_second = '".$a_starts_second."', description = '".addslashes($sessionVars["SELL_description"])."', pict_url = '".addslashes($sessionVars["SELL_pict_url"])."', category = ".$sessionVars["SELL_sellcat"].", minimum_bid = '".$sessionVars["SELL_minimum_bid"]."', reserve_price = '".(($sessionVars["SELL_with_reserve"]=="yes")?$sessionVars["SELL_reserve_price"]:"0")."', buy_now = '".(($sessionVars["SELL_with_buy_now"]=="yes")?$sessionVars["SELL_buy_now_price"]:"0")."', bn_only = '".$sessionVars["SELL_buy_now_only"]."', auction_type = '".$sessionVars["SELL_atype"]."', adultonly = '".$sessionVars["SELL_adultonly"]."', duration = '".$sessionVars["SELL_duration"]."', duration_second = '".$sessionVars["SELL_duration_second"]."', minimum_users = ".intval($sessionVars["SELL_minimum_users"]).", increment = ".doubleval($sessionVars["SELL_customincrement"]).", international = '".(($sessionVars["SELL_international"])?"1":"0")."', ends = '".$a_ends."', ends_second = '".$a_ends_second."', photo_uploaded = ".(($sessionVars["SELL_file_uploaded"])?"1":"0").", quantity = ".$sessionVars["SELL_iquantity"].", relist=".intval($sessionVars["SELL_relist"]).", relisted=0, closed='0', private='n', item_value = '".$sessionVars["SELL_item_value"]."', number_of_bids = '".$sessionVars["SELL_number_of_bids"]."', bid_value = '".$sessionVars["SELL_bid_value"]."', suspended='".$SUSPENDED."',"; $query .= "current_bid=0, num_bids=0, WHERE id = '".$sessionVars["SELL_auction_id"]."'"; $backtoclosed=true; if($BPLowbidAuction_TESTMODE == 'yes'){ echo $ERR = $ERR_9999; }else{ $res=mysql_query($query); if (!$res) { MySQLError($query); exit; } $auction_id=$sessionVars['SELL_auction_id']; $sessionVars["SELL_auction_id_old"]=$auction_id; $query = "DELETE FROM BPLA_bids WHERE auction='$auction_id'"; $res = @mysql_query($query); if(!$res) { MySQLError($query); exit; } Thanks in advance for any help and replies! Hey everyone. So I am coding a badge system for my website usersystem. I am trying to think how I'll handle issues before actually starting to code it and one issue I just can't seem to figure out how to handle.. How would I limit the amount of MySQL results to show per line. Eg. A user has 6 badges but I'd only like to show 2 per line. So in total it'd show 3 lines with 2 badges per line. If that makes any sense? Is there any way possible to actually do this? I have a problem displaying the results of a table, It shows them in one long list and I'd like them to show as 2 or 3. I had a look around and the most favoured way to this I found was to split the results either by odd/even or using percentages but Im having trouble implementing it into my script. How would I go about adding the odd/even way to this: <?php $query = mysql_query('SELECT * FROM users ORDER BY Username'); while ($row = mysql_fetch_array($query)) { if ($row['UserID']) ?> <b>Username:</b> <span class=class1><a href="aeditprofile.php?username=<? echo $row['Username'] ?>"><? echo $row['Username'] ?></a></span><br> <b>Group:</b> <? echo $row['Level'] ?></color><br /><hr> <?php } ?> Essentially I'm after getting something like this: Name Name Name Group Group Group and so on down the page.... I'm working on a website that uses a database to display the employees from different states. Below is the code I'm using and everything works great, but I can't figure out why all the results are getting posted twice. I'm trying to isolate just one state so we can have a different contact page for each state. Thanks for any help! Please let me know if you need more information. (I'm attaching a screenshot of what's happening as well.) Code: [Select] <? include "public/public_common.php"; //Open Database Connection $db = open_db_connection(); $sql = "SELECT DISTINCT state_full = 'california' from users where active = 'Y' and show_on_contactus = 'Y'"; $results = mysql_query($sql, $db); if(!mysql_num_rows($results) == FALSE) { while($row = mysql_fetch_array($results, MYSQL_BOTH)) { echo "<ul id=\"directors\">\n"; $state_sql = "SELECT * from users where active = 'Y' and show_on_contactus = 'Y' and state_full = 'california' order by last_name"; $state_results = mysql_query($state_sql, $db); if(!mysql_num_rows($results) == FALSE) { while($state_row = mysql_fetch_array($state_results, MYSQL_BOTH)) { echo "<li>\n"; echo " <div class=\"fl dirimg\">\n"; if($state_row[photo] == "") { echo "<img border=\"0\" width=\"61\" height=\"85\" src=\"images/exe_placeholder.jpg\" alt=\"$state_row[first_name] $state_row[last_name]\" />\n"; } else { echo "<img border=\"0\" width=\"61\" height=\"85\" src=\"n2team/pictures/$state_row[photo]\" alt=\"$state_row[firstname] $state_row[last_name]\" />\n"; } echo " </div>\n"; echo " <span class=\"fr\">$state_row[first_name] $state_row[last_name]<br />\n"; echo " $state_row[title]<br />\n"; echo " $state_row[city], $state_row[state]<br />\n"; //echo " <a href=\"mailto:$state_row[email]\">$state_row[email]</a></span></li>\n"; } } echo "</ul>\n"; } } ?> this is my code but i want to have a pice so if their is no results the it will put in a message like "No Results" but i cant figger it out <?php $host="localhost"; $username="xxxxx"; $password="xxxxxx"; $db_name="xxxxxxx"; $tbl_name="Shows"; // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name WHERE Month='April'and Year='2011' order by Day asc "; $result=mysql_query($sql); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <table width="400" border="1" cellspacing="0" cellpadding="3"> <?php while($rows=mysql_fetch_array($result)){ ?> <span class="elevenbold"><? echo $rows['Day']; ?> <? echo $rows['Month']; ?> <br><strong class="elevenboldblue"><? echo $rows['Song']; ?></strong><br><? echo $rows['Data']; ?></span><br><br> <?php } ?> </table> </td> </tr> </table> <?php mysql_close(); ?> Hello, This is query in MySQL Quote mysql> LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number); Query OK, 0 rows affected (0.00 sec) Records: 2200 Deleted: 0 Skipped: 1200 Warnings: 0 Now, I am trying to run the same query in PHP and display the same results.... (i.e. Records, Deleted, Skipped) Quote <?php $db=mysql_connect("localhost", "user", "1234") or die(mysql_error()); $dname="database"; mysql_select_db($dname)or die(mysql_error()); $sqlstatement="LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number)" ; mysql_query($sqlstatement) or die(mysql_error());; echo "it is done!"; ?> Tried mysql_fetch_array, row but could not get it to work... please help guys What's the best way to format results from a MySQL table? I've found very vague examples of PHP code utilizing html tables. Below is my current PHP. Thanks! <?php $con = mysql_connect("localhost","xxxxx","xxxxx") or die('Could not connect: ' . mysql_error()); mysql_select_db("addresses", $con); $result = mysql_query("SELECT * FROM addresses"); while($row = mysql_fetch_array($result)) { echo $row['first_name'] . " " . $row['last_name'] . " " . $row['extra_info'] . " " . $row['address'] . " " . $row['city'] . " " . $row['state'] . " " . $row['zip']; echo "<br />"; } mysql_close($con); ?> How can I limit the amount of time my while loop to only show the first 4 rows of my SQL table?
I am using this code to loop my whole table:
while($row = $results->fetch(PDO::FETCH_ASSOC)) { echo ' <li>Mileage: '.number_format($row["Mileage"]).'</li> <li>Engine size: '.$row["EngineSize"].'cc</li> ';} ?>I only want to loop through the first 4 rows of my SQL table, I then want to duplicate the same code but start at the 5th row until the 8th row of the table, how can I do this? Thanks, Nick I would like to modify my php script where my PDF search results would not only display the company name, the country, but also display a limit number link by pages so that not all of the results are shown. I also want the first word searched to go to the first occurrence of the word on the PDF document. What would be the best way to do this? Here is my code: <html> <head></head> <body> <?php if (!isset($_POST['q'])) { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search</h2> <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> <input type="text" name="q" size="30" /> </form> <?php } else { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search Results</h2> <?php try { // create object // $swish = new Swish('/usr/local/apache/htdocs/swish/index.swish-e'); $swish = new Swish('/var/www/html/pdf2/index.swish-e'); // get and run query from command-line $queryStr = htmlentities($_POST['q']); $result = $swish->query($queryStr); ?> Found <?php echo $result->hits; ?> match(es) for '<?php echo $queryStr; ?>'. <?php // iterate over result set // print details for each match while($r = $result->nextResult()) { ?> <p> <?php echo $r->swishreccount; ?> <strong> <a href="<?php echo '/pdf2', ltrim($r->swishdocpath, '.') ; ?>"> <?php echo $r->swishdocpath; ?> </a> </strong> (sco <?php echo $r->swishrank; ?>) <br/> <?php echo $r->swishdocpath; ?> </p> <?php } } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } } ?> </body> </html> Any assistance would be greatly appreciated. Edited by mac_gyver, 15 May 2014 - 08:17 AM. code tags please Hi Everyone,
I have a question about pagination. I have this code that I would like to incorporate into my php file.
This is said code that will be incorporated:
try { // Find out how many items are in the table $totalItems = $databaseHandle->query(' select count(*) from tableName ')->fetchColumn(); // Set how many items per page to display $limit = 10; // find how many pages are needed $totalPages = ceil($totalItems / $limit); // Find out which page we are on $currentPage = min($totalPages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array( 'options' => array( 'default' => 1, 'min_range' => 1, ), ))); // Calculate the offset for the query $offset = ($page - 1) * $limit; // Some information to display to the user $start = $offset + 1; $end = min(($offset + $limit), $total); // "back" link $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($currentPage - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>'; // "forward" link $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $totalPages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>'; // Display the paging information echo '<div id="paging"><p>', $prevlink, ' Page ', $currentPage, ' of ', $totalPages, ' pages, displaying ', $start, '-', $end, ' of ', $totalItems, ' results ', $nextlink, ' </p></div>'; // Get the results. Paged query $stmt = $databaseHandle->prepare(' select * from tableName order by name limit :limit offset :offset '); // Bind the query params $stmt->bindParam(':limit', $limit, PDO:: PARAM_INT); $stmt->bindParam(':offset', $offset, PDO:: PARAM_INT); $stmt->execute(); // Results? if ($stmt->rowCount() > 0) { $stmt->setFetchMode(PDO::FETCH_ASSOC); $iterator = new IteratorIterator($stmt); // Display the results foreach ($iterator as $row) { echo '<p>', $row['name'], '</p>'; } } else { echo '<p>No results could be displayed.</p>'; } } catch (Exception $e) { echo '<p>', $e->getMessage(), '</p>'; }and this is what is in my php file: <html> <head></head> <body> <?php if (!isset($_POST['q'])) { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search</h2> <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> <input type="text" name="q" size="30" /> </form> <?php } else { ?> <img src="/wvb-logo-slogen.png" border="0" /> <h2>Search Results</h2> <?php try { // create object // $swish = new Swish('/usr/local/apache/htdocs/swish/index.swish-e'); $swish = new Swish('/var/www/html/pdf2/index.swish-e'); // get and run query from command-line $queryStr = htmlentities($_POST['q']); $result = $swish->query($queryStr); ?> Found <?php echo $result->hits; ?> match(es) for '<?php echo $queryStr; ?>'. <?php // iterate over result set // print details for each match while($r = $result->nextResult()) { ?> <p> <?php echo $r->swishreccount; ?> <strong> <a href="<?php echo '/pdf2', ltrim($r->swishdocpath, '.') ; ?>"> <?php echo $r->swishdocpath; ?> </a> </strong> (sco <?php echo $r->swishrank; ?>) <br/> <?php echo $r->swishdocpath; ?><br /> <?php $file = '/var/www/html/active_colist.csv'; $fh = fopen($file, 'r'); $companies = array(); $row = fgetcsv($fh, 1024); // ignore header while ($row = fgetcsv($fh, 1024)) { $companies[$row[0]] = array('company' => $row[1], 'country' => $row[3]); //changed line } fclose($fh); //Split a filename by . $filenames = explode(".", $r->swishdocpath); //get 3 chars from $filenames to $country $wvb_number = substr($filenames[1],1,12); $country = substr($filenames[1],1,3); echo 'Country: '.$companies[$wvb_number]['country']."<br />"; //echo 'Country Name: '.$country."<br />"; //$filenames[2] = explode(".", $r->swishdocpath); $year = substr($filenames[2],0,4); echo 'Year: '.$year."<br />"; //$filenames = explode(".", $r->swishdocpath); //$wvb_number = substr($filenames[1],1,12); echo 'WVB Number: '.$wvb_number."<br />"; echo 'Company Name: '.$companies[$wvb_number]['company']; //echo 'Country: '.$companies[$wvb_number]['country']; ?> </p> <?php } } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } } ?> </body> </html>My question is what would be the best way incorporate this into my php file so that I am able to display a limit number link by page so that not all of the results are listed on the same page? If that is even possible. I'm ready for the next step on my site, which is learning how to filter results down with a second search. The scenario is: A viewer searches for a plant by 4 variables to describe the leaf. After submit, they go to the results page, with 200 paginated results. (This is where I've gotten to) Now, on that same page, they choose to further narrow their results by searching those 200 results for plants that have purple flowers. Maybe they get 40 results and can use another variable to narrow further - and so on. What's the best way to set this up? I've been looking into temporary tables, but it seems to be a challenge because the table deletes the moment they leave that page or close the connection? Sessions seem like another possibility, but I read there's security issues. What's the best way to set this up? Just re-query the database with the entire set of variables from both the first and second searches? is it quicker to build some type of permanent table with a timestamp that I can use to delete it after the user has gone away? Hi guys, Having problems sorting mysql results. I can easily order/sort table columns but would like to order the results by a variable.(Distance in Miles). Havent much experience in PHP and really struggling with this. Basically a query echoing out car make and models and how far they are located from a postcode. Can get it to work no porblem, but not to order/sort by least distance. Heres what i'm working with: Code: [Select] $res=mysql_query("SELECT * FROM cars"); while ($row = mysql_fetch_assoc($res)){ echo $row['Make']; echo $row['Model']; //variable will be determimed by user input form $postcode="W12 3SR"; $start=$postcode; $ends = array(); //finds value from database field { $ends[]=$row['Location']; } // Postcode entered by user via input form $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$start'"); while($row=mysql_fetch_array($result)){ $gridn[0]=$row['Grid_N']; $gride[0]=$row['Grid_E']; } foreach($ends as $fin){ // Postcodes within mysql table $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$fin'"); while($row=mysql_fetch_array($result)){ $gridn[1]=$row['Grid_N']; $gride[1]=$row['Grid_E']; } // TAKE GRID REFS FROM EACH OTHER TO WORK OUT DISTANCE. $distance_n=$gridn[0]-$gridn[1]; $distance_e=$gride[0]-$gride[1]; // CALCULATE THE DISTANCE BETWEEN THE TWO POSTCODES AND DIVIDE BY 1.6 TO CONVERT KM TO MILES $hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e))/1.609; //VARIABLE FOR DISTANCE AND ROUNDED OF TO NEAREST WHOLE NUMBER. $distance=''.round($hypot/1000,0).''; echo " $distance miles"; echo "<br>"; } } ?> I wish i could just do something like this but isnt possible, is it ? Code: [Select] "Select * FROM cars ORDER BY $distance"; Thanks! I've got a page that displays all my blog entries on a single page. When you click on a specific entry, it pulls the post ID and loads the page specifically. From there, I wanted to have the option to click either onto the next or previous post by finding the next or previous ID in the database.. however, I know that sometimes posts are deleted, etc. so the ID's won't exactly be in order. What direction should I take with this? Been using a function I found here a while back for listing categories and sub categories and it works perfect. Code: [Select] function listSubcats ($parent, $level=0){ global $abc; $sql = "SELECT id, title FROM Cat WHERE parent = $parent"; $res = mysqli_query($abc, $sql); while (list($id, $title) = $res->fetch_row()) { $indent = str_repeat('-', $level); echo "<OPTION value='$id'>$indent $title</OPTION>\n"; listSubcats ($id, $level+1); // list its subcats } } But this is the first time I need change the way the results are displayed. And that leads me to realizing I am a bit confused on how list really works. The mysql table has the typical ID, CatName, parent I need to have each Cat with all subcats related to it listed in its own div. But whatever I try I cannot get the placements of the opening and closing divs in the right spots. So can anyone tell if its even possible to do it with this function. I did work it out using multiple queries but then read on alot of forums that queries inside while statements is not good. Just looking for he best (Correct) way of geting the results laid out properly. like this Code: [Select] <div class="one-third column"> Cat1 </div> <div class="one-third column"> Cat 2 </div> <div class="one-third column"> Cat 3 - Subcat 1 - Subcat 2 -- Sub Subcat 1 </div> <div class="one-third column"> Cat 4 </div> Hope that makes sense... Thanks for any guidance. I'm needing some direction in how to start this... I have a page with the 50 U.S. states listed. I have a column in my mysql database that holds each state's name called: source There's a few thousands rows in my database, so the state names vary in the record count. How can I query the database and have a little count by each one of my 50 states that shows how many results exist in the db for that state? I know how to query for total rows and show that number... but confused on how I would do it for individual line items. Thanks for any suggestions. Here is my HTML code: Code: [Select] <html> <head> <title>Simple Search Form</title> </head> <body> <form name="searchform" method="get" action="/search.php"> Select Gender: <select name="gender"> <option value="Male">Male</option> <option value="Female">Female</option> </select> Select City: <select name="gender"> <option value="all">All Cities</option> <option value="newyork">New York</option> <option value="toronto">Toronto</option> <option value="london">London</option> <option value="paris">Paris</option> </select> <form> </body> </html> Here is my PHP code: <?php // get the data from the search form # get the gender (male or female) $gender = $_GET['gender']; # get the city $city = $_GET['city']; // connect to mysql and select db mysql_connect('localhost', 'root', 'pass') or die(mysql_error()); mysql_select_db($test_db); // send query $query = mysql_query("SELECT * FROM `visitors_location` WHERE gender='$gender' AND city='$city'"); $count = mysql_num_rows($query); // display data while ( $show = mysql_fetch_assoc($query) ) { echo $gender . " " . $city; } ?> My script basically shows # of males or females in a specific city. How can I show all males in all cities? In other words, let's say I want to show # of Females from all those 4 cities combined. I don't know how to do that. Can someone please help me? Hi All, Below is my code to add the two different query results into one. This is working fine when both the queries have same no.of rows. eg: row1 = 1 2 3 (Query1) row2 = 3 5 5 (Query2) o/p: 4 7 8 Let's say, I have few rows which are not exactly matched with first query. eg: row1 = 1 2 3 2 (Query1) row2 = 3 empty empty 5 (Query2) o/p : 4 2 3 7 (I want the o/p to be like this) empty means there is no data from the second query. In my while, && working fine when the 2 queries have same no.of rows. while (($row1 = mysql_fetch_assoc($rs1)) && ($row2 = mysql_fetch_assoc($rs2))) { $strHtml .= "<tr>"; $strHtml .= "<td align=center colspan=3>".($row1['Calls']+$row2['Calls'])."</td>"; $strHtml .= "<td align=center colspan=3>".($row1['actual_duration(min)A']+$row2['actual_duration(min)A'])."</td>"; $strHtml .= "<td align=center colspan=3>".($row1['call_usage']+$row2['call_usage'])."</td>"; $strHtml .= "<td align=center colspan=3>".($row1['disconnection_charge']+$row2['disconnection_charge'])."</td>"; $strHtml .= "<td align=center colspan=3>".($row1['total_revenue']+$row2['total_revenue'])."</td>"; $strHtml .= "</tr>"; } Is the while loop i am using correct or there is any other better solution for this? please help me, Thanks in advance. I am trying to display certain MySQL data based off of what link is clicked. For example.. I want to display all the entries from 2009 when a link for 2009 is clicked; maybe like.. <a href="http://website.com/page?yr=09">2009</a> But I am having trouble doing so.. any help would be great! P.S. The years are in my database with only the last two numbers.. 10, 09, 08, etc. $result = mysql_query("select setlist_id, month, day, year, name, venue, location, label1, set1, set2, set3, encore, notes, photos, recording, poster from $database_table order by setlist_id DESC, year, month, day",$db) or die_now("Could not select setlists"); while($row = mysql_fetch_array($result)) { $the_id = $row["setlist_id"]; $the_month = $row["month"]; $the_day = $row["day"]; $the_year = $row["year"]; $the_name = $row["name"]; $the_venue = $row["venue"]; $the_location = $row["location"]; $the_label1 = $row["label1"]; $the_set1 = $row["set1"]; $the_set2 = $row["set2"]; $the_set3 = $row["set3"]; $the_encore = $row["encore"]; $the_notes = $row["notes"]; $the_photos = $row["photos"]; $the_recording = $row["recording"]; $the_poster = $row["poster"]; echo("<div class='date' id='date' tabindex='0'>" . "$the_month" . "." . "$the_day" . "." . "$the_year" . " - "); echo ($the_name != '') ? "" . "$the_name" . " - " : ''; echo("" . "$the_venue" . " - " . "$the_location" . "</div>"); echo("<div class='set'>" . "$the_label1" . ":<br /></div><div class='list'>" . "$the_set1" . "<br /></div>"); echo ($the_set2 != '') ? "<div class='set'>Set Two:<br /></div><div class='list'>" . "$the_set2" . "<br /></div>" : ''; echo ($the_set3 != '') ? "<div class='set'>Set Three:<br /></div><div class='list'>" . "$the_set3" . "<br /></div>" : ''; echo ($the_encore != '') ? "<div class='set'>Enco <br /></div><div class='list'>" . "$the_encore" . "<br /></sdiv>" : ''; echo("<div class='line'></div>"); echo nl2br("<div class='notes'>" . "$the_notes" . "</div>"); } When I replace the $result line with... $result = mysql_query("SELECT * FROM `$database_table` WHERE `year` = '09' order by setlist_id DESC, year, month, day",$db) or die_now("Could not select shows");... I get all the results from just 2009, which is what I want, but I want the results to depend on what link has been clicked. I hope I am making sense. Hey Everybody, I am writing a SUPER SIMPLE script and for some reason I cannot figure this issue out. I guess I'm too close to the situation and have spent too many hours staring at this script. Here's the problem: I am running a basic SQL query through php that should return multiple rows of data and instead returns the first row multiple times. I'm not sure what the problem is, but I'm sure YOU can help! <?php //Get Invoice Rows $sql = 'SELECT * FROM timecard WHERE INVOICE_ID=\'1000\''; $result = mysql_query($sql); $rows = mysql_fetch_array($result); $num = mysql_num_rows($result); //Build Current Invoice $i=0; $invoice = '<table class="invoice" cellspacing="0" cellpadding="0">'; $invoice .= '<tr class="heading"><td>#</td><td>Invoice</td><td>Date</td><td>Time In</td><td>Time Out</td><td>Hours</td><td>$/Hr</td><td>Sub Total</td></tr>'; while($i < $num){ if( $i%2 ) { $eo = 'odd'; } else { $eo = 'even'; } $invoice .= '<tr id="invoiceRow" class="'.$eo.'"><td>'.$rows[0].'</td><td>PHG'.$rows[1].'</td><td>'.$rows[2].', '.$rows[4].' '.$rows[3].', '.$rows[5].'</td><td>'.$rows[6].'</td><td>'.$rows[7].'</td><td>'.$rows[8].'</td><td>'.$rows[9].'</td><td>'.$rows[10].'</td></tr>'; $runningTotal[$i] = $rows[10]; $i++; } //Get Total $total = array_sum($runningTotal); $invoice .= '<tr><td colspan="7" style="background-color: #000000; color: #ffffff; font-weight: bold; padding-left: 5px;">Total</td><td align="right" style="background-color: #333333; font-weight: bold; color: #FFFFFF; padding-right: 5px;">'.$total.'</td>'; $invoice .= '</table>'; echo $invoice; ?> Much thanks in advance for anyone that is able to resolve this problem, even just a try is nice!! Thank You, E |