How to get the next id from mysql? - php

I'm trying to get the ID from the next row in MySQL database. How exactly would I do that? The code I'm currently working with the following code. I'm semi-new to PHP and SQL and also 15, so please be understanding if this isn't exactly right.
Here's what I have so far:
$GetNext = "SELECT * FROM sheep WHERE id = '> $row[id]' AND owner = $_SESSION[user_id] AND barn = $row[barn] AND pasture = $row[pasture]";
$get = mysqli_query($conn, $GetNextLeft);
$row = mysqli_fetch_assoc($get);

With 'LIMIT' we can get 1 data.
We sort by 'ORDER BY id ASC' we sort by small to large size.
$GetNext = "SELECT * FROM sheep WHERE id > $row[id] AND owner = $_SESSION[user_id] AND barn = $row[barn] AND pasture = $row[pasture] ORDER BY id ASC LIMIT 1";

You can do this using order by and limit such as:
select s.*
from sheep s
where id > ? and . . .
order by id desc
limit 1;
The ? is a reminder that you should be using parameters in your queries, rather than munging query strings with input values.

You mean the first id greater than row['id']? You should ORDER BY the id, than use limit to get only the first row.

Related

PHP Query LIMIT DESC not working properly

I am trying to get a list of highscores (top 10) of players that played my game.
Everything works except for one thing, the list isn't right.
The first 10 people are correct, but when i go to page 2 the list isn't further going done.
Variables Explain
$gamemode = "Endless"
$filter = "Score"
$startNum = Page1 = 0, Page2 = 10
$maxlimit = 10
Query:
$query = "SELECT ID, Gamemode, Name, Score, ContainersSaved, TimePlayed, Date, ScorePerMinute
FROM $dbName . `highscore`
WHERE Gamemode='$gamemode'
ORDER by `$filter` DESC
LIMIT $startNum, $maxlimit";
Does anyone know what im doing wrong?
If your Score field is varchar try: (or change it to INT)
$order=$filter;
if($filter=='Score') {
$order="ABS($filter);
}
$query = "SELECT ID,Gamemode,Name,Score,ContainersSaved,TimePlayed,Date,ScorePerMinute FROM $dbName . `highscore` WHERE Gamemode='$gamemode' ORDER by $order DESC LIMIT $startNum, $maxlimit";
I fixed it, i forgot to change the 'Score' field from varchar to an INT, so it was trying to Descend on string instead of INT.
Thanks to the tip Imaginaerum gave me :)

How to get the first ID with SQL

I am trying to get the first id with a specific date.
So this is my code:
$checkm = "SELECT FIRST(id) FROM times WHERE date='2014-03-07'";
$resultm = mysqli_query($con,$checkm);
I have a table called times and there are some columns. Two of them are date and id.
I am trying to get the first row's id with the date 2014-03-07.
EDIT: Fixed!
$checkm = "SELECT id FROM times WHERE date='2014-03-06' ORDER BY id ASC LIMIT 1";
$resultm = mysqli_query($con,$checkm);
while($row = mysqli_fetch_array($resultm)) {
$resultm1 = $row['id'];
}
You probably want the minimum id.
SELECT min(id)
FROM times
WHERE date = '2014-03-07'
pretty straightforward...
SELECT id FROM times WHERE date='2014-03-07' ORDER BY id ASC LIMIT 1

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

PHP add many rows to database

I have problem with database. I want to add about 10 new rows after pageload. It should check if there is an article with id (that is actually loading). If its not, add 10 of that id with different tag id.
$sprawdz = "SELECT id_artykulow FROM tag_art WHERE id_artykulow='".$_GET['id']."' " ;
$miasto = mysql_query($sprawdz);
$a = mysql_num_rows($miasto);
while ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1";
$sw = mysql_query($zm);
while($row3=mysql_fetch_array($sw)){
$zmienna = "INSERT INTO tag_art(id_artykulow, id_tagow) VALUES ('".$_GET['id']."', '".$row3['id']."' ) ";
$cokolwiek = mysql_query($zmienna);
}
$a++;
}
There is two tables. One tag_content with id (of the tags), and another tag_art with id_artykulow (= id of the article) and id_tagow (id of the tag taken from tag_content)
Don't know why, but it doesn't add 10 rows (it should be for example ten id_artykulow = 10, with different id_tagow). How to fix it?
Thx for help and let me know if u need more informations (like more code etc.)
why do you have 2 while loops?
cant you just replace
while ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1";
with
if ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);
or just let the databse do all the work by:
$query = "INSERT INTO tag_art(id_artykulow, id_tagow) SELECT '".$_GET['id']."', id FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);
(and i would also recomendate protection agains sql-injections, mysql_real_escape_string())
Or let the database do all the work:
// store id as mysql-variable, but let php force it to an integer first
mysql_query("SET #id = " . (int) $_GET['id']);
// calculate how many new art we need, to get 10, using greatest to avoid negative numbers
mysql_query("SELECT #art_needed := GREATEST(0, 10 - COUNT(*)) FROM tag_art WHERE id_artykulow = #id");
// Need to use prepere to be able to have an mysql-variable as limit
mysql_query("PREPARE art_stmt FROM 'INSERT INTO tag_art(id_artykulow, id_tagow) SELECT ?, id FROM tag_content ORDER BY RAND() LIMIT ?'");
// execute the query using the mysql-variables
mysql_query("EXECUTE art_stmt USING #id, #art_needed");
just reread my old answer, and no longer agrees with "or just let the databse do all the work by" for that answer, the database could do alot more.

Categories