SELECT LAST and FORELAST Values - php

I want to make a SELECT command, which selects the last and forelast value of my table in my database.
$sql = "SELECT * FROM beitrag WHERE beitrag_id=101 OR beitrag_id=102";
At the moment I am only selecting it manually.

Use the order by and the limit clauses, like so:
$sql = "SELECT * FROM beitrag ORDER BY beitrage_id DESC LIMIT 2;";
Basically, we order by the id in descending order so that the highest one is the first, and we select only two elements (limit), so first "last" and "forelast".

Related

Fetching data with Group by, How to select the latest or greatest id? (PHP to MySQL)

I wanted to fetch data from MySQL with PHP when a user inputs something. I have this code.
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid";
$result = mysqli_query($con, $query);
It works fine however, it fetches the oldest or first data from the group. How do I select the newest data?
I've search and found possible solutions by using FROM, JOIN, IN, etc. However, I do not know how to use them since I only know the basics. Hopefully someone could explain one solution for me.
There is a simple solution that you can do.
You can order your data to DESC order. I'm sure that you have an id(primary key) in your table.You just have to order all your datas' to DESC order of ids .So that your last inserted data set will be the one to be fetched since it's on the top.
change your query to: (add your primary key(in the following query i have added it as id) in the ORDER BY syntax)
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid ORDER BY `ID` DESC"
Just add a condition in your query which only retrieves the row having the greatest id.
Find out the id first and then you can use the same query for that id:
SELECT MAX(id) FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid
After getting the id and storing it in a variable (say $temp):
SELECT * from mealplans where `id` = $temp

Retrieve table ID from selected row

So I've been stuck on this for a while and I can't find anything on google for this specific thing.
I have this small snippet of code
$link = mysqli_connect("localhost", 'username','password',"database");
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Which should select the latest table by order of id's right?
Well what I want to do is return this id. So if I have 5 items/rows I want to grab the latest (5 in this case) id of the table, and return it. With the eventual goal of using this returned id in javascript but that's a worry for later, right now I just want it in plaintext where the result should only be the id.
This is probably a duplicate question but I can't for the life of me find what I should google to get there
EDIT:
I guess I should clarify further. I know I'm able to do
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
but whenever I try to actually retrieve it/print it its returned as a string instead of the ID.
EDIT 2: I, thanks to some comments, have managed to figure it out. Sorry for the badly worded everything, I'm new to this and as I said don't know how to word it.
SOLUTION:
After just throwing away the $sql thing I added:
$result = mysqli_query($link,"SELECT * FROM `uploads`");
Then I simply did
echo mysqli_num_rows($result);
To echo out the number of rows/what I called the "ID".
Sorry for all the confusion, thanks to those that tried to help. To the others there's no need to be rude.
If I understood your question correctly, you want to get the ID field only, so you have two options:
Option 1 (Recommended)
Given your code
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Change it to:
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
This way, your getting just that ID field you're after. Nothing else is returned from each row.
Option 2
Keep your sql query as it is, and get the ID field from each row in your results (it's an array, so you can retrieve only one field by using its index or name).
Of course, I assume there's an ID field in your table!
Just select the ID.
SELECT id
FROM uploads
ORDER BY id DESC
LIMIT 1;
Simply select what you want.
$sql = "SELECT id FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
The * means you want to select every column there is. However, SQL gives you the possibility to select the specific columns you want. You could also do something like
$sql = "SELECT id, name, title, somethingelse FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
and you'd receive these 4 fields as an array.

Ordering by a value that is not in the database where selecting from

how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count

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.

How to do a MYSQL Select dependant on a previous MYSQL Select

My problem is that I need to SELECT fields from a MYSQL table depending on a previous MYSQL SELECT. Before I did this through an if and else if statement when it could only be one of two things but now I've added a third and so this no longer works. This is the effect I want:
$call = "SELECT * FROM blog_posts WHERE id = $_GET[id] LIMIT 1";
$latest = mysql_query($call);
$result = mysql_fetch_array($latest);
$post_cat = $result['category'];
$sql="SELECT title, post_thumb, id FROM blog_posts WHERE category = $post_cat AND id <> $_GET[id] ORDER BY id DESC LIMIT 6";
Thanks in advance.
$sql="SELECT `title`, `post_thumb`, `id` FROM `blog_posts` WHERE category = '".$post_cat."' AND `id` = '".$_GET[id]."' ORDER BY `id` DESC LIMIT 6";
Put tables/columns in backticks and surround PHP variables in concatenated quotes. At the moment, your query asks MySQL to find a value in the category column which is $post_cat. Not the PHP variable $post_cat, the explicit string $_post_cat.

Categories