mysql select statement and limiting the number of records - php

I am coding a blog post kind of thing, where the author will post the article and it will be displayed in the front end, my problem starts for selecting the posts as i have to meet certain conditions for posting the news in the front end,
I have 4 fields in the database namely
title
pic_title
pic_brief
pic_detail
you guessed it right apart from the title table the rest of three will hold the path to the images in varchar datatype, which will be used to display as the post, the format of the front end is such that
a) there will be total of eight post
displaying in the front end (eight
entries from the database)
b) there will be three post on the top which will include the value from
the table title, pic_title and
pic_brief (total of 3 values)
c) and the rest five will contain just the title and pic_title
(excluding the three entries of top)
Please NOTE: i want the second query to exclude the top 3 record
which already exist in the top i.e
(first query = 3 post in descending
order, second query = 8 - first 3 = 5
post)
The Order of the Post i want is by id DESC
EDIT: I took the first query as
SELECT * FROM news ORDER BY id DESC LIMIT 3
Now if i take the same second query and try populating the values by desc order again the same records will be accessed
In simple words i want a query that will skip the last three records order by id DESC
How do i achieve this feat in PHP?

If you just want the SQL, here it is:
First query
SELECT * FROM `table` LIMIT 3
Second query
SELECT * FROM `table` LIMIT 3,5
(where table is the name of your table of course. Of course you may want to add some ORDER BY clause. To execute these queries in PHP, I suggest reading the manual. If you have any specific problems after doing so, then you can post a new question.

This is a situation where I'd likely opt to select all eight records at once - the less trips to the database, the better.
SELECT t.title,
t.pic_title,
t.pic_brief
FROM TABLE t
ORDER BY t.id DESC
LIMIT 8
...because the rest is just presentation:
$query = sprintf("SELECT t.title,
t.pic_title,
t.pic_brief
FROM TABLE t
ORDER BY t.id DESC
LIMIT 8");
// Perform Query
$result = mysql_query($query) or die( mysql_error() );
$rowcount = 1;
// Use result
while ($row = mysql_fetch_assoc($result)) {
if(rowcount <= 3) {
echo $row['title']
echo $row['pic_title']
echo $row['pic_brief']
} else {
echo $row['title']
echo $row['pic_title']
}
++$rowcount;
}

first query will be like this
"select title, pic_title , pic_brief from table_name order by post_id desc limit 0 , 3"
and rest of five will be
"select title, pic_title from table_name order by post_id desc limit 3 , 5"
second query will exclude the three results returned by first query...
If you want more perfection you can collect all three Ids returned by first query and can add NOT IN in second query.
"select title, pic_title from table_name where post_id not in (1,2,3) order by post_id desc limit 0 , 5";

Related

How select next row pagination in sql

I'm sorry I'm weak for English.
i echo 2 row in each page . how echo next 2 row
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category
WHERE mzmx_post.id = mzmx_post_category.post_id AND zmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2
You can use the two-arguments form of LIMIT to offset the result by a given number of rows, like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2, 2 -- fetch records 3 and 4
This gives you the second page. If you want the third page, then:
LIMIT 4, 2
And so on.
Note that I modified your query so the joining condition between the tables is placed in the ON clause of the join rather than in the WHERE clause.
Better add one extra column (e.g. mzmx_post_key bigint) of Long type in each table and have sequential value on that column. Use that column to fetch data from DB from page wise.
sqL suery should look like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5 and mzmx_post_key> ##last record key##
ORDER BY mzmx_post_key ASC
LIMIT 2
The basic idea is to use
LIMIT n,o
where n is the results per page
o is the offset from the first result
for the p-th page the offset would be
o = p * n
where p = 0,1,2,....

in SQL/PHP returning id with the highest and 2nd-5th highest date

As said in the title, I need FIVE queries that returns the ID for rows with the 1st-5th most recent date.
Table: film
id releasedate
232143 2013-06-20
536523 2013-07-20
453554 2013-08-20
098776 2013-09-20
549302 2013-10-20
i.e the first query would return the id 549302
I think this would work for the first query:
$first = $db->query("SELECT id, FROM film WHERE MAX(releasedate)" );
PS: Sorry for the poor formatting of this post, can anyone tell me how to display tables appropriately?
I need to display each id at different points on the web page. Simply returning a list of ids won't suffice. What I really need is for each id to be encapsulated into a unique variable so i can call them at different points on the web page.
No, you don't need five queries.
$first = $db->query("SELECT `id` FROM `film` ORDER BY `releasedate` DESC LIMIT 5" );
This will get the IDs from the database of the five most recent films in your table.
To access each of these just run through a while loop.
while($row = $first->fetch_assoc()) {
$row['id']; # Each ID will be available like this.
}
If you really need to do this in separate queries, you can use the 2-argument form of the LIMIT clause, which is LIMIT offset, count. To get the newest film, use
SELECT id FROM film ORDER BY releasedate DESC LIMIT 0, 1
To get the 2nd most recent film, use
SELECT id FROM film ORDER BY releasedate DESC LIMIT 1, 1
the next one is
SELECT id FROM film ORDER BY releasedate DESC LIMIT 2, 1
and so on.
But it should be better to get them all in one query with
SELECT id FROM film ORDER BY releasedate DESC LIMIT 5
You can then save them all in an array with:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ids[] = $row['id'];
}
Then you can use $ids[0] to display the most recent film, $ids[1] for the second most recent, and so on.

Mysql select last 20 rows, with while loop

I have 50+ rows and each have an id, how do i get the last 20 records and display each ones information with php.
Is the best way to use a loop? I want it to display the results quick and not miss any rows, is a loop the best way to go then?
This is the code that I have
$result = $mysqli_log->query("SELECT * FROM `$usern`");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
The MySQL query being executed doesn't specify any "order" to the rows; MySQL is free to return the rows in any order it chooses, so it's possible that the "last 20" rows on one run of the query might differ from the "last 20" rows on a second run.
(We do observe repeated behavior when the statement is re-executed; it usually takes some DML operations, the addition of an index, or an OPTIMIZE table statement, to actually get a change in the results returned... but the point is, there is no "last 20" rows in the table. In MySQL, it's just a set of rows.)
To specify a specific sequence of the rows, add an ORDER BY clause to the query. Assuming that you want to use the unique id column to order the rows, and you want the last 20 rows, and you want them returned in ascending id sequence:
SELECT t.*
FROM ( SELECT u.*
FROM `$usern` u
ORDER BY u.id DESC
LIMIT 20
) t
ORDER BY t.id
And, yes, processing rows "in a loop" in PHP, just like you demonstrate, is a normative pattern.
To limit the number of queries use Limit and order them desc by your ID
Select *
From `$usern`
Order By ID Desc
Limit 20
To Flip them back in the forward order you can use a derived table
Select *
From (Select ID, Test
From test
Order By ID Desc
Limit 3) d
Order By ID Asc
If you need the newest 20 records, you have to ORDER DESC the result set by ID and then LIMIT that set result to 20 records.
So you can
use something like this:
$result = $mysqli_log->query("SELECT * FROM `$usern` ORDER BY `ID` DESC LIMIT 20");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
Another good approach, if you are using associative keys like $row['credit'], is to use featch_assoc instead of featch_array (if your framework provides such a function)

mysql search by title in last 100 records

My case is, when someone is posting to my news web data with 600k records,
they can create the same title which someone just posted in the last few hours with same subject.
data: sid|title|desc|timestamp|userid
Usually I use:
select sid from ".$prefix."_stories WHERE title = '".$subject."' limit 0,1
It searches all data for $subject then notice poster if have they have the same title.
I need a query which searches in the last 100 records.
I tried the following, but this did not work:
select sid from ".$prefix."_stories WHERE title = '".$subject."' and sid > MAX(sid)-100 limit 0,1
You can do this with a subquery that returns the last 100 sid. Note, I have omitted the PHP concatenations for brevity here.
SELECT
last100.sid
FROM
(
SELECT
sid,
title
FROM $prefix._stories
ORDER BY sid DESC LIMIT 100
) last100
WHERE
last100.title = '$subject'
Assuming that you have a primary key, incrementing by 1 with every record (which will put newest at the bottom), just do this:
SELECT sid, title
FROM ".$prefix."_stories
ORDER BY sid DESC
LIMIT 100
This will select the last 100 records
Good point by Michael in my comments... Edit to code and further comment:
Removing the where clause, this will select the last 100 records... Run a loop to check to see if the title or summary already exists:
while ($row = $result) {
if $subject = $row['title'] {
$duplicate = TRUE;
endwhile;
}
}
Just compare the resulting data. Thanks Michael
Sort by sid (descending, so newest entries come first) and limit results to 100:
$sql = "select t.sid from (select sid, title from ".$prefix."_stories ORDER BY sid DESC LIMIT 0,100) t WHERE title = '".$subject."';"
Be sure to chek $subject to avoid SQL Injection (better: Use prepared statements / PDO).

Simplest way to get the next Row from an SQL table when I know the second one

Hi everyone I am trying to write a sorting script
For this my user will click a move up button which posts the id of the current selection we want to move up to a new page where the script is processed.
So using the fetch functions below i am getting the sort id of the current row we want to move up
$sqlCurrent = "SELECT * FROM `contact` WHERE `contact_id` = $id LIMIT 0, 1 ";
$resultsCurrent= mysql_query($sqlCurrent) or die(mysql_error());
$rowC = mysql_fetch_row($resultsCurrent);
$currentSort =$rowC[9];
I then pulled out all the data in decending order using
Now if my current sort order is 6 I want to look for the row with the sort order with 3 or 4 or 5 in order so i used the decending order and the next sort scrip comes up in the next table.
$sql = "SELECT * FROM `contact` ORDER BY `contact`.`contact_sortOrder` DESC LIMIT 0, 30 ";
The question is how do I simply get data from that row using 1 or maybe 2 functions.
We cant simply look for the next sort order because it is possible it wont be there.
For this example i have used a database like this
rowId 1 Sort order 6
rowId 2 Sort Order 2
rowId 3 Sort Order 4
Now I am row Id 3 and want to replace it with the next one. So i need to pick up rowId 2 somehow using the shortest method.
Any help will be useful
Could be as simple as
$query = "
SELECT
x,y,z
FROM
contact
WHERE
contact_sortOrder < $currentSort
LIMIT
1
";
(assuming $currentSort is safe for "direct insertion" into the query. see http://docs.php.net/pdo.prepared-statements)
select prev.*
from contact as curr
left join contact as prev on prev.contact_sortOrder < curr.contact_sortOrder
where curr.contact_id = $id
order by prev.contact_sortOrder desc
limit 1

Categories