PHP - Splitting Mysql Results?
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.... Similar TutorialsHello - hoping to find some direction with this. I think this is fairly simple for more experienced php coders but I'm having trouble with it. It's a php grep text string search that results in a list of files that contain the string.
Hoping to split the $results value (list of file names) into separate links to open the file. I was able to convert into a link for the first file listed, but it links to that same file for all the entries in the list. I assume that maybe an array of $results needs to be created first rather than try and work with $results at the end?
<?php /** * E.Yekta * cafewebmaster.com */ define("SLASH", stristr($_SERVER[SERVER_SOFTWARE], "win") ? "\\" : "/"); $path = ($_POST[path]) ? $_POST[path] : dirname(__FILE__) ; $q = $_POST[q]; function php_grep($q, $path){ $fp = opendir($path); while($f = readdir($fp)){ if( preg_match("#^\.+$#", $f) ) continue; // ignore symbolic links $file_full_path = $path.SLASH.$f; if(is_dir($file_full_path)) { $ret .= php_grep($q, $file_full_path); } else if( stristr(file_get_contents($file_full_path), $q) ) { $ret .= "$file_full_path\n"; } } return $ret; } if($q){ $results = php_grep($q, $path); } echo <<<HRD <pre > <form method=post> <input name=path size=100 value="$path" /> Path <input name=q size=100 value="$q" /> Query <input type=submit> </form> $results </pre > HRD; ?>Attached Files php_grep.php 908bytes 0 downloads Basically I have a date of birth field (date) now how would I go about splitting that date field into 3 variables $year $month and $day? Any small push forward is much appreciated, I have searched but it seems that I might not be putting it into words correctly. Actually while writing this I suppose I might of thought of the solution Code: [Select] <?php $year = date('Y', strtotime($row['dob'])); $month = date('m', strtotime($row['dob'])); $day = date('d', strtotime($row['dob'])); ?> Would that be how you would go about it? 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); ?> 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(); ?> 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? 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 hello, I have a search that matches users ISBN with two databases....code is below $query_search_exact_match = mysql_query("SELECT nvc_site.title, nvc_site.id, nvc_site.description, nvc_site.search_text, nvc_site.image, nvc_site.date, nvc_site.price, nvc_site.location_city, nvc_site_ads_extra.name, nvc_site_ads_extra.value, nvc_site_ads_extra.classified_id FROM nvc_site,nvc_site_ads_extra WHERE name = 'ISBN%3A' AND live=1") or die(mysql_error()); then i take the ISBN that the user entered and match that with the isbn's in the DB while ($fetch_extra = mysql_fetch_array($query_search_exact_match)) { $value = ereg_replace( "[^0-9]", "", $fetch_extra['value'] ); $to_find_isbn = mysql_real_escape_string(ereg_replace( "[^0-9]", "",$_POST['szs'])); if($value == $to_find_isbn) { echo "Match Found"; } else { echo "No Match Found"; } //ELSE doesn't work here.....it displays both the if and else at the same time } i need it to display no match found if there was no match found.....I am soo lost right now!! please help thank you I'm having a weird issue in which i'm trying to pull rows from a table based on the contents of specific fields. My query strings a $ms = ("SELECT * FROM games WHERE game = 'test' AND playername = '$test' OR opponentname = '$test' ORDER BY playdate DESC LIMIT 25") or die ('Error: '.mysql_error ()); Which works fine until later I try to use: $ms2 = ("SELECT * FROM games WHERE game = 'test2' AND playername = '$test' OR opponentname = '$test' ORDER BY playdate DESC LIMIT 25") or die ('Error: '.mysql_error ()); What is weird is on $ms2 I found if I change it to: $ms2 = ("SELECT * FROM games WHERE playername = '$test' OR opponentname = '$test' AND game = 'test2' ORDER BY playdate DESC LIMIT 25") or die ('Error: '.mysql_error ()); It works... on one page, on the rest neither line works it just pulls every row in the table that fit one of the two name fields. Has anyone experienced anything like this or know why or a fix for this? Thanks! 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! This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=347295.0 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 having two issues:
(1) The correct mysql query for multiple rows
(2) The if/elseif/else to pull data from these rows, and process it based on the row data
I'm only pulling data where A=1 and B=1,2 -- so two possible entries there (call them B1 and B2). I need a php if statement to choose whether the output of B is one of two urls (b1=google,b2=bing). The actual script is far more complex, with more than just 1,2 from B. I've stripped all the excesses down to this one if/else issue and the db query. The output php doesn't matter here. And I can add more elseif once this problem is solved. <?php mysql_connect(localhost, $db_username, $db_password); @mysql_select_db($db_database) or die("No connection"); $query = "Select * FROM table WHERE column='stuff' AND parent='1,2' ORDER BY id DESC LIMIT 10"; $query_result = mysql_query($query); $num_rows = mysql_num_rows($query_result); mysql_close(); ?> <?php for($i=0; $i< $num_rows; $i++){ //start a loop $stuff = mysql_result($query_result, $i, "column"); $row = mysql_fetch_assoc($query_result, $i); if($row['parent'] == 1) { $url = 'http://google.com'; } else { $url = 'http://www.bing.com'; } ?>My own first attempt at a if/then was 500. I got help on another site to redo it (new code shown here), but the new if/else always show the else (Bing). It was also at this time that I learned that "1,2" only showed 1. Hoping that this site is far more friendly than StackOverflow. . Edited by kpmedia, 17 December 2014 - 07:22 PM. 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 join two tables but I am producing no results. I'm convinced that I have entered everything correctly, but clearly I haven't? Can anyone spot my mistake?
<?php require 'core/memberinit.php'; $member = new Member(); include 'timeago.php'; $memberid = $member->data() ->id; if(isset($_GET['q'])) { $q = html_entity_decode($_GET['q']); $query2 = DB::getInstance()->query("SELECT c.id c.time as time, c.message as message, c.removed1, c.removed2, m1.member_first_name as firstname1, m1.member_last_name as lastname1, m1.username as username1, m2.member_first_name as firstname2, m2.member_last_name as lastname2, m2.username as username2 FROM conversation c LEFT JOIN members m1 ON c.member1=m1.id LEFT JOIN members m2 ON c.member2=m2.id WHERE (c.id=$q OR c.originalid=$q) AND ((c.member1=$memberid AND c.removed1='No') OR (c.member2=$memberid AND c.removed2='No')) ORDER BY c.id"); foreach ($query2->results() as $result2) { echo $result2->firstname1; echo $result2->lastname1; echo $result2->username1; echo timeAgo(strtotime($result2->time)); echo $result2->message; echo $result2->firstname2; echo $result2->lastname2; echo $result2->username2; } ?> Edited by MartynLearnsPHP, 23 November 2014 - 12:55 PM. 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 guys, i'm trying to search from a form and use php to display the results of the FullText Search from a MySQL database, but I don't get any results from the query. This is the query: $query="SELECT * FROM tutorials WHERE MATCH(title, tags) AGAINST ('$searchform')"; I think the query is right but it doesn't give me any results.... Does anyone know what could be wrong? I think it might be something wrong with my table (database). my table should have 5 columns: id, title, category, content, tags The form should search throught the title and tags columns to see if it finds anything matching the $searchform , but I don't think it is doing it. Can anyone help please? 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. |