PHP & MySQL - Limiting an array - php

I'm trying to limit the array mysql_fetch_assoc($query), and am unsure on how I would go about it.
$query = mysql_query('SELECT * FROM table ORDER BY id DESC');
while($output = mysql_fetch_assoc($query))
{
//do something
}
Do you add a counter or something? How do you add this counter?
I'm really confused about mysql_query and mysql_fetch_assoc. Please Help!

After your ORDER BY id DESC, add LIMIT 100 (or whatever number you want). For the next 100 rows, use LIMIT 100,100, then LIMIT 200,100 and so on.

You can limit the results directly in the SQL query. To get the top 100 records do
SELECT * FROM table
ORDER BY id DESC
LIMIT 100

Use LIMIT
SELECT * FROM table ORDER BY `id` DESC LIMIT 10;
Haven't you seen phpMyAdmin always limiting to 30?

Related

How to select the top third row in mysql

Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.

Mysql select list after a specific id

I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.

Did I mess up my where clause? Getting unexpected results

$active_sth = $dbh->prepare("SELECT * FROM user_campaign
WHERE status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
AND uid=:uid
ORDER BY status ASC");
$active_sth->bindParam(':uid', $_SESSION['uid']['id']);
$active_sth->execute();
I am positive $_SESSION['uid']['id'] = 7
but it will also pull results of id 10 or any other number.
Is my AND/OR clause written wrong?
Yes, query is wrong
SELECT * FROM user_campaign
WHERE (
status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
)
AND uid=:uid
ORDER BY status ASC
You have to group all ORs to make sure that row got one of this values, and separately check if it have given uid.
The proper way to write that is:
SELECT * FROM user_campaign
WHERE status IN ('blasting', 'ready', 'followup_hold', 'initial_hold')
AND uid =: uid
ORDER BY status ASC
You should use IN instead of that huge amount of ORs :)

there is something wrong with sql query

following sql query was working fine, i don't whats wrong i did its stopped fetching records.
$data = mysql_query("SELECT * FROM product_table where pid=$saa1 OR gpid=$saa1 OR
category_id=$saa1 ORDER BY autoid desc limit $no2,20")
or die(mysql_error());
when i remove or clause its works fine for example
$data = mysql_query("SELECT * FROM product_table ORDER BY autoid desc limit
$no2,20")
or die(mysql_error());
please have a look and let me know where i am doing mistake....
regards,
It seems,your query is OK, but when you use WHERE clause, you limit the results , so perhaps there is no recored for display, especially when you use LIMIT for starting offset and number of results.
Your query is ok but there is no record to satisfy your where part. go to your database and create some new rows with your criteria.
Try:
$data = mysql_query("SELECT * FROM product_table where (pid=$saa1 OR gpid=$saa1 OR
category_id=$saa1) ORDER BY autoid desc limit $no2,20")
or die(mysql_error());

Limit FOREACH in MySQL PDO query

I am using the below code to try and echo out the latest 5 entries on the MySQL table, I cannot, however seem able to figure how to limit the number of results, can anyone help me out by allowing me to limit the number of results to 5 rows?
<table>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/resources/pdo.php");
$q = "SELECT * FROM `content` ORDER BY `id`";
$query = $pdo->query($q);
$data = array_reverse($query->fetchAll());
foreach ($data as $row) {
echo "<tr><td>{$row['title']}</td><td>{$row['id']}</td></tr>";
}
?>
</table>
Thanks!
Please note that I am new to PHP and I need help so if this question isn't useful, help me because I have only just started this.
Use LIMIT clause in your SQL query:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
From the manual:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
Use the LIMIT word:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
order by id desc to get rid of the array_reverse and limit 5 to cap the number of returned results.
$q = "SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5";
...
$data = $query->fetchAll();
As a global guideline: when writing queries try to formulate them in such a way that the resultset is as close to what you need as possible, ie no extra sorting or filtering operations afterwards.
having the dbserver send data that you aren't going to use is a waste
having to resort/refilter data on the webserver costs webserver performance and, in the case of big resultsets, it can cost lots of memory as well
When pulling data from a database you normally set a LIMIT via the MySQL-query, instead of counting the loop-iterations when reading the returned data.
$q = "SELECT * FROM `content` ORDER BY `id` LIMIT 5";

Categories