Retrieve table ID from selected row - php

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.

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

How to insert a particular value from one database table into another using '$row'?

I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)

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.

Can`t MAX() function be used with mysqli?

I can not find a proper answer to this question. I have a very simple code for making a query in mysql to select the row with the maximum value in a determined column (called popularity) from a table (called comments). Every row has a column named comment_id
here is the code:
$connect_error = 'Sorry, try again, there was a connection error';
$con = mysqli_connect('localhost','user_name','password') or die($connect_error);
mysqli_select_db($con, 'database') or die($connect_error);
$result = mysqli_query($con, "SELECT MAX(`popularity`) FROM `comments`");
while ($row = mysqli_fetch_assoc($result)) {
$most_popular = $row['comment_id'];
}
echo "most popular is: $most_popular";
mysqli_free_result($result);
mysqli_close($con);
the screen does not show a proper result. Can someone give me an advice in this regard?
Thank you
You are looking to display the comment_id field, but you don't have that in your SELECT query. You are only selecting the max popularity value, and nothing else.
Try this for your query:
SELECT comment_id FROM comments ORDER BY popularity DESC LIMIT 1
This is sorting your comments by popularity, and then just picking the top one.
Of course you can easily change that to select more columns or even a SELECT * if you want to be able to display other values in this record.
To select the row with max 'popularity' column use this query;
$result = mysqli_query($con, "SELECT * FROM `comments` ORDER BY `popularity` DESC LIMIT 1");
In case you want all sorted by popularity remove the LIMIT 1...
You need
SELECT MAX(`popularity`) AS comment_id FROM `comments`
This will give the column the correct name for the associated array.
You are trying to read the result from a column named comment_id when the result from your query will be named MAX(popularity)
Run this query in mysql "SELECT MAX(popularity) FROM comments" first.The output of this gives you the index to use with $row[index] ie first row which in this case the index will be popularity else just change $row[content_id] to $row[popularity]

Categories