Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




How To LIMIT Results In Html Php/sql Query?


I need to limit results in the following query type:

http://www.somewhere.com/php/sql-a....ql_order=&pos=1

I found a reference that says I should be able to use LIMIT x[,y], but
I don't know where/exactly how to add that to the string. Once I know
what it's supposed to look like, and can write something to generate
it.

If someone could post an example using the above and limiting the
output to 100 records starting at position.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Display Results From Query In HTML-table
I'm working with PHP3 and Oracle 8. Can anyone tell me how to display the results from a query into my HTML-table?

Output Query Results To Html Table
I have a MySQL table "products" and I want to output product's data to html table as below:
- A products contain 4 fields: image, name, description, price.
- 4 products is nested in 1 html table 4 rows x 4 columns.

Code:

Limit Db Query Limit Output
I'm using php 5  - recent mysql  -  This code was designed to display 2 colums of user input.  10 in each column.

Both cols display just fine-  my problem is after the colums display the rest of the db is displayed underneath of them.

Why is this happening and how can i fix it so that only the 20 items chosen are returned?

This db is expected to grow quite large so even querying the entire db will eventually be costly to server performance. Code:

REGEX: Can't Seem To Replace LIMIT Clause In Query Using Preg_replace ($pattern, $replacement, $query)
Want to replace the limit clause in a query, but can't get it right.
What's wrong with this:

$pattern = "(.*)limit (.*)";
$replacement = '$1'
$replacement .= "LIMIT $limit";
$replacement .= '$2'
$query = preg_replace ($pattern, $replacement, $query);

Limit Sql Results
I am working on a site to display thousands of results....I have all of that working but I want to limit the results to 50 at a time...any suggestions on how to browse the results with a limit of 50....I am thinking about checking the value of a number and while it is less than the total count of rows in the query increment it by 50..

Limit Results Displayed
I have tried a few different tutorials etc on this but I cant get it to work properly with my code. What i need is the page to display 10 results per page and to automatically create a "Prev | 1 | 2 | 3 ..etc | Next" navigation that runs the results of the query.
PHP Code:

Limit Results To 20 Per Page.
I have a Database and script where it SELECT * FROM my database and lists the info on my website. I want to be able to limit the quary to only 20 per page. Here is an example of what i am talking about on this page http://sacvalleyhomes.com/Sacvalley/property_inquiry.php

Everything listed under Property Inquiry is genarated be my database. As it is now i have 5 diffrent tables for 5 diffrent pages. This is way to much work to keep updated.

What i want to do is put all 5 tables in to 1 table and have my php script only show the first 20 listing then generate the page numbers on the bottom or some way to view next 20 results and so on. Code:

Limit Mysql Results
I have a script which has a mysql query which returns 20 results - I want to add some validation so if my variable ($var) is empty, it only allows the user to select the first 5 results my code is: -

$sql = mysql_query("SELECT * FROM greetingcards_cards WHERE category='$cat' LIMIT $from, $max_results");
while($row = mysql_fetch_array($sql)){   
        $image = $row['url'];
       $cardid = $row['cardid'];
        echo "<br><img src="$image" /><br><a href="?function=sendmessage&cardid=$cardid">Pick this card</a><br>";}

I want it so that if the variable is empty, instead of displaying "Pick this card" it displays - "You must register to pick this card" and have a different hyperlink Is this type of validation possible? if so how is it done?

Limit The Foreach() Results
I am using Magpie to parse an rss feed. My question is, do you know if you can limit the for each results?

foreach ($rss1->items as $item ) {
$title = $item[title];
$url   = $item[link];
echo "<a href=$url target='_blank'>$title</a></li><br>
";
}

Right now it echoes how ever many feeds are in the rss feed, I would like to limit it to the most recent 5.

Limit Search Results To 75 Characters?
I am working on a small search engine to put into my site to search the text on my pages. Right now all my page's text are being held in my database and displayed on my actual pages using php.

Anyways, I have so far limited my search results to the first 75 characters, then given the user a link to the page that the keyword they searched for resides on. The problem is that some of the keyowrds occur after the 75th character. Is there a way to display 75 characters with the keyword being in the middle of those 75 characters? Code:

Limit Query Result According To A Criteria
I have the following code which doesn't work:

"SELECT COUNT(*) AS total FROM $table_name
WHERE certain criteria HAVING total<=100";
The query above doesn't work and i get zero results.

In general the query take lots of time mainly because the criteria is not specific enougth and I get many many hits. I want to stop the query after getting the first 100 hits according to a certain criteria. When I use LIMIT 0,100 and not HAVING i get result from the first 100 records in the table but my table contain few million records.

Memory Limit Reached During CLI Query, Or What?
Running a CLI script that fopen's a file, parses the lines into an
array, checks the array entries against a few regular expression
qualifiers (i.e. !eregi("bot",$entry)) and dump the good entries into
a MySQL db.

The fopen'ed file is a 410MB text file with log entries formatted like
a .CSV file ("" text qualifiers and comma separators).

Running the script from a web browser in Windows98: Works fine, except
it stops about 1/10th of the way through (@~40MB).

Running the script via CLI on the RH9 server: Works fine, except I get
"Terminated" about 3/4rs of the way through (@~300MB).

Am I running into a memory useage issue or what? There's no
distinction between the last entry run successfully and the one after
that, in the log file dump, and everything goes into the db
fine...until the script terminates.

The Windows98 machine is running 512MB/PC133 DRAM with a 120GB HDD,
connected via a full T1 to the RH9 server with the MySQL db.

The RH9 server is a production server (I know...but I'm running out of
options on where to process this behemoth text file!) running 1GB RAM
and twin 60GB HDDs.

I will probably take what I have, trim the file to the remaining
entries, and append to the db, however I would like to understand why
the script is cutting out.

Sort Results By Date/time, Limit 5 Database Entries Of Today &/or Upcoming Days
I'm designing a website for my fraternity and in the database I have entries which contain past events, todays events, and upcoming events.  My problem is that I can not figure out how to sort the query results to display:
 
1) only past events based on the CURRENT DATE
2) only the events which fall on the CURRENT DATE or after, limiting the results to 5 entries
3) all events that fall on CURRENT DATE or afterwards

Example:   
Today is  September 15, 2007

Problem 1) Displaying all events that happened before September 15, 2007
Problem 2) Displaying only 5 results that fall on September 15, 2007 or after
Problem 3) Displaying all events that are happening on or after September 15, 2007

And obviously I would like the CURRENT DATE to change depending on what date it is, currently.

Ok so now I've been very redundant in my explanation of my problem here is the code and a link to what that particular page looks like. Code:

Memory Limit For For HTML Pages??
I have a php program that is building a grid (HTML table) from a MySQL
database. The problems started when I added a dropdown menu to the grid and
when I did the form buttons would not work when there were a few values in
the drop-down. If I removed the values so it was an empty drop-down menu the
form buttons would work. I thought there was a problem with my drop-down
which is a quite simple menu.

However, what I discovered is that it has to do with the size of the table
that I am building. I changed the query so that it would only pick up about
1/2 the records (134 vs 248) which is where it works (the 135th record
causes the buttons to quit working. It is not a data problem because I then
tested with a different set of data and it would also fail but at a
different spot.

I must be running into some kind of memory limit but I have no idea what it
is! Can someone help?

Getting Too Many Results From A Query!
This is very peculiar -- for some reason, I'm getting 6-8 results from each
of these queries, although only one listing matches. I have a pair of forms
on one page:

<FORM>
Search for lastname: ____________ [Submit]
</FORM>
<FORM>
Search for email: ________________ [Submit]
</FORM>

This goes to a searchresults.php page:

if ($searchname !== "") {
$query="SELECT artistID,firstname,lastname,email,city,state,count ry
from artists WHERE lastname='$searchname'";
$result=mysql_query($query) or die(mysql_error("Could not execute
query."));
while($row = mysql_fetch_array($result)) {
$alt_artistID = $row['artistID'];
$alt_firstname = $row['firstname'];
$alt_lastname= $row['lastname'];
$alt_email = $row['email'];
$alt_city = $row['city'];
$alt_state = $row['state'];
$alt_country = $row['country'];
echo "<CENTER><HR>".$alt_artistID."<BR>"
.$alt_firstname." ".$alt_lastname."</A><BR>"
.$alt_email."<BR>"
.$alt_city.", ".$alt_state." ".$alt_country."<BR>
<A HREF=delete.php?aritstID=".$alt_artistID.">DELETE THIS
LISTING?</A><BR></CENTER>";
}
}

The second section is identical except for:
if ($searchemail !== "") {
$query="SELECT artistID,firstname,lastname,email,city,state,count ry
from artists WHERE email='$searchemail'";
etc...
}

I don't understand why I would get 6-8 records when you can look at them and
see that all but one clearly do not match...?

Using Query Results
Can you use a queries results only once? In this script I'm looping through a query and saving some values in an array. A little further through the script I need to use the same query for output. When I loop through nothing is echo'd to the browser. When I output a row count it shows that the correct number of records, so they must still be there.

Query Results In 2 Columns?
I'm struggling to figure out how to do this properly. I have done a mySQL
query to extract a list of names, and done a mysql_num_rows to determine how
many results I've gotten. I want to split the list in to two columns. I've
created $percol = $mysql_num_rows/2 but I'm not quite sure how to "loop"
through the first half of the list, echo </td><td> and then list the
balance. Can anyone give me some guidance on how best to structure this?

Finding The Results Of A Query
I am working on a script that will query a database for a FNAME/LNAME
combo. If it finds the combo, I need it to do one set of instructions.
If it doesn't find it, I need it to do something else. What I can't
figure out is what variable to check against. Here is what I have for
the relevant part of the script:

$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($databasename) or die ("Cannot connect to database"
..mysql_error());
$query="SELECT FNAME, LNAME FROM (table) WHERE FNAME=('$FName') AND
NAME=('$LName')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
mysql_close($connection);

I tried checking the value of $result to see if it changed depending on
whether or not it found the selection. It does not. I just can't figure
out what to use for:

if (some expression){
perform this code
}
else{
do this
}

Grouping Results Of Query
I'm brand new to PHP (just starting today to convert tons of
ColdFusion/Access code to PHP/MySQL). There is a function in
Coldfusion that I can't find an equivalent to in PHP. Here is
what I am trying to do:

If I have a query that results in this information:
State Firstname Lastname
Idaho Terry Pratchet
Vermont Dan Brown
Vermont Bob Smith
Virginia Alice Johnson
Virginia David Jones

I would like to output the info like this:

But all I can find in PHP is a way to loop through the query
and show every row... if you are familiar with Coldfusion,
what I am looking for is something similar to this:

<CFOUTPUT GROUP='State'>
#State#<BR>
<CFOUTPUT>
#Firstname# #Lastname#
</CFOUTPUT>
<BR>
</CFOUTPUT>

Is there a function that does this in PHP, or do I need to
write code that watches the value of 'State' and manually
takes care of things whenever it changes?

ODBC Query Results
Consider the following:

<?

$username = "foo";
$password = "bar";
$host = "db";

$connect = odbc_connect("$host", "$username", "$password") or die;

$query = "SELECT id, name, address, city, state, comments1, comments2
FROM data.table1, data.table2 WHERE id = ô˜'";

$result = odbc_exec($connect, $query);

while(odbc_fetch_row($result)){
$id = odbc_result($result, 1);
$name = odbc_result($result, 2);
$address = odbc_result($result, 3);
$city = odbc_result($result, 4);
$state = odbc_result($result, 5);
$zip = odbc_result($result, 6);
$comments1 = odbc_result($result, 7);
$comments2 = odbc_result($result, 8);
print("ID: $id<br>Name: $name<br>Address: $address<br>City:
$city<br>State: $state<br>Zip: $zip<br>Comments1:
$comments1<br>Comments2: $comments2<br>
");

}
?>

Only one record is returned from data.table1 (containing the id, name,
address, city, state, & zip). However, there are multiple records
returned from data.table2 (records from comments1 & comments2). What
is happening is that when I run this script, all of the data returned
from data.table1 is printed over & over again along with each record
returned from data.table2. How can I make it such that id, name,
address, city, state & zip are only printed once - and allow comments1
& comments2 to be printed multiple times for each occurance in the
database?

I've thought about just creating a second database query for the
records in data.table2, however I need the join I'm getting by using
the existing query.

For what it's worth, I'm connecting to a DB2 database using PHP /
Apache on Linux.

I'm confused by this.

Losing Query Results!
If I make a query;

$result = mysql_query($theQuery, $db);

and then make use of the query results like so;

while ($row = mysql_fetch_row($result)) {

//do something with query results}

I can't use $result again, I have to make another query! Why is this and is there any way around it?

Multiple Sql Query Results
I'm trying to do a query from 2 databases. Basically i have
catagories within 2 databases. If both catagories return 0 rows then it
does nothing but if one or both have rows returned then i need it to
echo a result. I guess where i'm wondering if there's an OR statement i
can use or something to that effect...

something like

if($numrows == 0 OR $numrows2 == 0) {
echo ('');
}else{
echo ('$result');



SQL Query - Results From Another PHP Page ?
Can I store this PHP code in another page, then refernece it on
multiple pages using Require or Include ???

//results from sql query
for ($i=0; $i<$number; $i++) {
$ID = mysql_result($result,$i,"ID");
$CompanyName = mysql_result($result,$i,"1");
$ContactName = mysql_result($result,$i,"2");
$Phone = mysql_result($result,$i,"3");
$HomePhone = mysql_result($result,$i,"4");
$MobilePhone = mysql_result($result,$i,"5");
$AltPhone = mysql_result($result,$i,"6");
$SecondContact = mysql_result($result,$i,"7");
$SecondPhone = mysql_result($result,$i,"8");
$ThirdContact = mysql_result($result,$i,"9");
$ThirdPhone = mysql_result($result,$i,"10");
$Notes = mysql_result($result,$i,"11")

Sql Query Results And Scrolling
I make a mySQL database query and display the first 10 results. Then
the user can click on "next" link to get the next 10 results. How can
I do that without issuing the sql query again? Can I keep the results
from the first query?

Query In PHP Won't Return Results In There's Only 1
$sql = 'SELECT `PageTitle` '
$sql .= 'FROM `Pages` '
$sql .= 'WHERE `PageID` = 1 LIMIT 0, 30'

I have run this query in MySQL control panel and it works perfectly.
When I try to do it via PHP I get no results.

If I select all rows (i.e I don't specify a "WHERE") I get one fewer
rows returned than there actually are.

Tabulating Sql Query Results
I'm trying to number my rows in the column named "Pos" but so far I not getting any success, someone please bail me out find below my script, this script displays my results fine but without my Positions (Pos); Code:

Combining Query Results
I have two queries which searches for any fixtures your clan (team) is in and then returns some information about the fixtures. Is there any way of combining these results and ordering them by date? Code:

Filtering Results With Php Query
This code works, but I don't know how to filter the results to where only one person is displayed..it displays all records with similar address or state or city, I would like to know how to make it display only one person when multiple search fields are entered.

I'm using PHP5, and I have searched the forums but I'm not sure exactly if I found what I'm looking for...I don't know much about php or mysql. Code:

Capturing/using Results Of Query
I would like to display/capture/use the URL's that are displayed on a web page after making a query to a forum.
What do I mean?

I am part of a forum that uses vBulletin.  One option is to display the forum topics that have had posts that day, i.e. active topics.

Essentially, when you click on the link:
http://www.somedomain.com/forum/search.php?do=getdaily

the resultant page has a list of the active topics, highlighted as links.

What i would like to do is capture/access that resultant page and use regular expressions to grab the URLs.  I can do the RegEx but I cannot seem to capture that resultant page.

How Do I Show Results Of A Query
I know how to connect to a Mysql table.  I want to run the query and show the results on my page.  I'll have about 25 different fields I need to show on the page.  Most of this information will be a couple of addresses. 

Basically, a billing and then a shipping address.  Can someone show me how to show some of this on a page?  I'll need to align all this stuff around the page. 

Filter Results Of Query
I am modifying some pages in CRE Loaded.

allprods.php list all currently active products and I added a manufacturers column that displays who makes that product.

I want to allow shoppers to filter the product list so that it shows only products from a particular manufacturer.

I have gone through several scenarios in my mind, but nothing I've thought of seems simple and bullet proof.

One of the issues is that the all products query includes all manufacturers.  If I were to put a variable in the query to select only a particular manufacturer, how would I code it so it does not interfere with the all products query?

Would logic based upon the value of a form action work?  If form action exists, someone wants to filter.  If not form action or form action = all, then they want the whole list. Seems like filtering a list is pretty common and there should be an easy solution.

Formatting Problem With Query Results
I have a minor problem with a script. I have written a piece of code (do...while loop) that will return results of a query a row at a time, with the proper formatting in a table. Everything works fine when there are results to lay out in the table. The problem arises when the query yields no results. When this happens, the loop below iterates once (without data) instead of not executing at all:

$result2=mysql_query("select * from ...) or die("");
$myrow2=mysql_fetch_array($result2);

do {

...bunch of stuff...

}

while($myrow2 = mysql_fetch_array($result2));


Where do we go from here?

Combining Results From MSQL Query
I have the following 2 queries which each produce a result. I have spent hours reading up and have searched devshed but I can't find how I would go about Adding these two numerical results together using PHP.

Query 1

$sql = "SELECT SUM(total) AS total_price FROM detail_tourdet WHERE voucher_id = '$voucher_id'";
$result = mysql_query ( $sql );
$row=mysql_fetch_array($result);
echo $row['total_price'];

Query 2

php $sql = "SELECT SUM(total) AS total_price FROM retail_acom WHERE voucher_id = '$voucher_id'";
$result = mysql_query ( $sql );
$row=mysql_fetch_array($result);
echo $row['total_price'];

Sorting Database Query Results
I want to know if it is possible to sort query results so that the records with a value in a certain field is displayed first and the records with the field empty thereafter.

Sorting Query Results Into Groups
I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID.

I've attempted this using a query for each possible status, which I
figure was pretty inefficient (plus it didn't work properly). The best
I could do manually was to just display a list of staff and their
statuses sorted in order of the title ranks.

Display Query Results In A Table
$sql = "SELECT name FROM employee_tb;
$result_query = @mysql_query ($sql);// run the query
while ($row = mysql_fetch_array($result_query,MYSQL_NUM)){
$name = $row[0];}
// assuming i have 8 results

how can i display the results from this query in a table with 3 rows each column?

Query Results And Affected Rows?
I'm doing a mass database update and I have a query string something like this:

UPDATE table SET field1=0, field2='' WHERE (email='address1' OR email='address2' {and so on...} );

I know you can view how many rows were changed after its done. I'm wondering though, is there a way I can view which entries failed? For example, lets say the email address - 'address34' was not found in the database, is there anyway I can display this from this UPDATE query? or to do this, would I have to compare each address individually with the table to check if it exists? (and if it matters I have about 1000 adresses that are being updated from this)

Query Results With Multiple Keywords
The way I have it set up now, a form results in 2 keywords, namely Keyword and Keyword2 using 1 text field, and one select field. In the text field, the person enters in the City, in the Select field, they choose a state, which abbreviates it to 2 letters.
Now, for the code that is supposed to process this: Code:

Exploding Results Of Mysql Query
I have a table with times and dates listed like this:

0000-00-00 00:00:00
2003-09-20 20:26:22
etc
etc

What I want is to query the DB for the field (matchdate) and then get it to explode the ' ' to give jsut the date for me and then put it into a dropdown in a loop. this may sound easy but i too sleepy to work it out and searching aint good.

Sql Query Not Returning Correct Results
i'm using an entry in an sql database as a semaphore and it,
unfortunately, doesn't appear to be working. the script that spawns
the child processes has a for loop that performs the same basic sql
query over and over again until the value has changed (there's a one
second delay between each query). unfortunately, the resultant row is
always the same, even when the other process *has* changed it. as an
example, if the orig. value was of the entry was 0, and one second into
the execution of the second process, the entry was changed to 1, my
program would, even 10 seconds later, fetch 0. in other words, it'd
never be aware of the change.

any idea as to why this is and what i can do to fix it?

Aligning Multiple Query Results
I'm trying to pull data from 2 different tables and do a loop to
retrieve more than one row. I'm having problems with aligning the
information. Can someone lead me in the right direction? I've done some
looking myself and found something called GROUP BY? Is that what I need
to use?

Checking Lenth Of Query Results
If I return a result from a query with mysql_fetch_array and need to check the character length of a specific field, what is the best way? I have tried mysql_field_len but am getting errors with the code below: PHP Code:

Arrays, Query Results And Select Box
I want/need to pre-select a drop-down box with a value if it's present in both a lookup table and user account table. After wrestling with this for a few hours I give up.

i know this can't be this complicated, but apparently i'm missing something, so if anyone can suggest a way to go about this i'd be a little more sane. The idea is to have the user value already selected then when they change the value i'll update their account.

I Need To Export Query Results To A .txt File.
Here's some code:

I need this info displayed on a .txt file that is updated each time that text file is called up. So if a new result is added, when that text file is called up I need that new listing to appear there. Or every time a new result is added, it updates the text file. Whichever makes the most sense, I'm not sure.

How To Truncate Multiple Query Results....
I have a news section on my website, where the article(s) are stored in a MySQL database. Titles in one column, article body in another. On the actual page, I have a limited space to which to print the content, and need to truncate it so it does not overlap, or stretch the content div and blow the design out of whack.

When only returning one article from the db, I can do this easily, however, the problem is that not all articles are/will be lengthy enough to fill the div. In such cases, I want to return the next article, up to the remaining div space, then truncate it.

For example, right now, the article that's being displayed fills up more than the allotted space, so it's truncated. But the next three articles I post may be short, where I'd need all three plus a segment of a fourth to fill the space. Using Dreamweaver MX2k4 I can do this by "repeating that region", but limiting the number of characters is only applicable to each query, not to the overall div. As such, it won't work in the way I need. Code:

MySQL Query Not Returning All Results
I have a user table in the DB, for example:

+---------+----------------+-------------------+
|     uid     |     username     |       firstname       |
|----------+----------------+------------------+
|       1     |       cobby        |       Andrew          |
|       2     |       admini        |     test-account    |
+---------+-----------------+------------------+

If, in phpMyAdmin, I query:
   SELECT `username` FROM `users`;

It will return results correctly (cobby and admini, respectively).
But if I make a simple PHP script, such as:

<?php

mysql_connect('localhost', 'cobby', 'dbpass');
mysql_select_db('testdb');

$query  = mysql_query('SELECT `username` FROM `users`');
print_r(mysql_fetch_assoc($query));

?>

It only returns:
Array ( [username] => admini )

Why does it only return the second result? I have a feeling I'm doing something really silly, but I looked over this test script and its got me stumped.

Using Arrays With Mysql Query Results
im currently in the process of making a piece of code that will firstly take all the data from a table in mysql and then assign it to an array. This data will consist of several different rows of data each with different infomation for each field in the table.

i want to be able to use an array in a loop so that depending on which number of the loop is on will change the infomation that is assigned to a certain array. Code:

I Get The Number Of Raws From A Query, But Can't See Results
I get the number of raws from a query, but can't see results?

Putting A Line Break In Query Results
Quick question, how would you go about putting a line break after a certain number of results pulled from a query? What happens is I get too many results and it stretches the page, thus looking awful. So what I want to do is print half of the results on one line, use a line break <br /> and display the other half.

So instead of results that are say....
A B C D E F G H I J K L M N O P Q R S

I want....
A B C D E F G H I J
K L M N O P Q R S


Copyright © 2005-08 www.BigResource.com, All rights reserved