How to get data from 2 tables? [duplicate] - php

This question already has answers here:
Querying 2 Tables in a single query
(3 answers)
Closed 8 years ago.
I am trying to create a website with an existing database.
The database has two tables, one of them contain the post info like title, id, content, etc etc,
the other table contains the post ID and the post category.
For example: I want to take a post from a specific category.
$sql = 'SELECT * FROM posts WHERE status = "publish" ORDER BY date DESC LIMIT 10';
This is a simple function, can some one help me please how to modify it, to get the category from the other table and the post info from the other table.

SELECT * FROM posts, posts_category WHERE category = 'category'
AND
status = 'publish'
AND
posts_category.post_id = posts.id
ORDER BY date DESC LIMIT 10;

$sql = "SELECT * FROM posts WHERE status = 'publish' AND pid IN (SELECT pid FROM pcategory WHERE ptype='category_name') ORDER BY date DESC LIMIT 10";

Related

SQL query to get all posts from a table in the db but max 5 entrys from a specific user? [duplicate]

This question already has answers here:
Using LIMIT within GROUP BY to get N results per group?
(14 answers)
Closed 2 years ago.
I´m building a php-blog system and want to display all posts but max five from each user on the start page.
I thinking of do this with a query in the database, but I´m lost on how to do that.
The count() function I guess will come in handy, but can somebody help me
This is my function today, and I just whant to improve it to get max five posts from each user
protected function getAllPostsDB() {
$sql = "SELECT recipes.Recipe_ID, recipes.Title, recipes.Short_description, recipes.Step_by_step,
recipes.create_date, recipes.last_mod_date, recipes.Portions, recipes.imgPath, users.Username
FROM recipes
JOIN users
ON recipes.User_ID = users.User_ID
ORDER BY recipes.create_date DESC";
$stmt = $this->connect()->query($sql);
/* fetch all is already set to associative array*/
$result = $stmt->fetchAll();
return $result;`
If you are running MySQL 8.0, just use window functions:
SELECT r.Recipe_ID, r.Title, r.Short_description, r.Step_by_step,
r.create_date, r.last_mod_date, r.Portions, r.imgPath, u.Username
FROM (
SELECT r.*, ROW_NUMBER() OVER(PARTITION BY User_ID ORDER BY create_date DESC) rn
FROM recipes r
) r
INNER JOIN users ON r.User_ID = u.User_ID
WHERE r.rn <= 5
ORDER BY r.create_date DESC
This gives the last five recipes per user, as designated by column create_date. You can change the ORDER BY clause of ROW_NUMBER() to some other column or set of columns if you want another sort rule.

ORDER before SELECT statement?

I have this query which works great
$sub_query = "SELECT * FROM posts WHERE post_status = 'published' AND
post_user = '{$out}' ORDER BY post_id DESC ";
The query brings back all of a specific users posts ordered by descending post id. The problem is it loops through every post user and orders them accordingly but I want the newest post overall not just the newest post per user.
Here is an image of the results to hopefully help explain better
You can see the query runs for a specific user and then moves on to the next user where I am trying to get the newest post id first
I have tried to follow this similar question but it brought back the same results.
$sub_query = "SELECT * FROM (SELECT * FROM posts ORDER BY post_id DESC)
T WHERE post_status = 'published' AND post_user = '{$out}' ";
Would I be able to order all of the selected posts first? Then use my where statement?
If you want the newest post per user, then remove the where and add a limit:
SELECT p.*
FROM posts p
WHERE p.post_status = 'published'
ORDER BY post_id DESC
LIMIT 1;
I did not understand if what you are looking for is
1) the list of the last post per user
2) the list of all posts sorted by the newest (regardless the user)
In both case you don't need to loop all users, you can extract data ordered just using the query itself (i strongely advise you on this solution).
option 1:
SELECT *
FROM posts
WHERE post_id IN (
SELECT MAX(post_id)
FROM posts
WHERE post_status = 'published'
GROUP BY post_user
)
ORDER BY post_user ASC
option 2:
SELECT *
FROM posts
WHERE post_status = 'published'
post_id DESC

Fetch new posts of random user from mysql

I want to fetch and display posts of different users as they upload a post.. i can access their posts by userid but the posts are in sequence and not random or new posts. For example if 2 users have posted 4 times, 3 times first user and 1 time 2nd in this sequence 1st user post, 2nd user post, 1 user ,1 user, my query will return the 3 posts of user 1 first and then single post of user 2 irrelevant of the original sequence and time(old/new).
My query is
//this is my table -> user_post(userid,post_id,post,time)
$query = "SELECT * FROM user_post ORDER BY (time) DESC WHERE userid = '$user_id'";
and i want to load only 4 latest posts and when i next refresh the field the next 4 posts must be loaded..
this is a Android Client-Server Based application and i'm using volley to make the http calls and exchange data using JSON.
Did you try to use the limit clause ?
You code would be like :
$query = "SELECT * FROM user_post ORDER BY (time) DESC WHERE userid = '$user_id' LIMIT 4";
You need to include a LIMIT clause inside your query:
$query = "SELECT * FROM user_post ORDER BY (time) DESC WHERE userid = '$user_id' LIMIT 0,4";
On every request you maintain a count of how many rows have loaded in $lastLoadedRow. The next several times you load you would do:
... LIMIT $lastLoadedRow,4;
... LIMIT $lastLoadedRow,4;
... LIMIT $lastLoadedRow,4;

MySQL show only the last 8 rows [duplicate]

This question already has an answer here:
MySQL LIMIT/OFFSET: get all records except the first X
(1 answer)
Closed 9 years ago.
On my index page I have the "latest work" which shows 8 portfolio pieces
and I need it to only grab the ones that have active = 1 as well
and I have something like this:
$sql = 'SELECT * FROM portfolio WHERE active = 1';
I tried doing this but its not working and i get errors when I try to pass it in PHPMyAdmin as well.
$sql = 'SELECT * FROM portfolio
WHERE active = 1
WHERE [id] > SELECT
MAX([id]) - 8 FROM portfolio';
Any ideas?
If you want to get the most recent 8 active pieces, use LIMIT as well as ORDER BY
$sql = 'SELECT * FROM portfolio WHERE active=1 ORDER BY id DESC LIMIT 8'
SELECT * FROM portfolio WHERE active=1 ORDER BY id DESC LIMIT 8
$sql = 'SELECT * FROM `portfolio` WHERE `active` = 1 ORDER BY `id` DESC LIMIT 8';
ORDER BY id DESC -> orders rows by highest to lowest value of ID, use ASC for opposite.
LIMIT 8 -> only 8 first rows

mysql select statement and limiting the number of records

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";

Categories