How to "shift" query result one row further - php

Let's say I have something like this:
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 2");
while ($row = $sql->fetch()) {
echo $row['title'];
}
So this grabs the 2 latest entries in a table and then echoes the designated column. How can I take the 2nd and 3rd most recent entries from my table ignoring the first one?
Right now I'm thinking about setting the limit to 3 and somehow skipping the first result and grabbing the 2 remaining.

Try this :
LIMIT 1,2
1 => offset : From where to start(First one will be 0)
2 => number of records
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 1,2");
while ($row = $sql->fetch()) {
echo $row['title'];
}

Related

Fetching last 100 row from mysql not working | JSON fromat

I'm trying to fetch the last 100 row but only one row is being displayed as a result
here is my php code:
<?php
require_once("variables.php");
$db = new ezSQL_mysql($GLOBALS['database_username'],$GLOBALS['database_password'],$GLOBALS['database_database'],$GLOBALS['database_server']);
header('Content-Type: application/json');
echo "{\"office\":\"0\",\"dept\":{\"desk\":[";
$symbols = addslashes($_GET['symbols']);
$symbolsArr = explode(",", $symbols);
foreach($symbolsArr as $s) {
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
echo json_encode($jsonArray);}
echo "]}}";
?>
UPDATE> based on recommendations below I have changed get_row to get_results but the code broken now and it's not displaying any error.
Read the documentation on the database class you are using (ezSQL):
----------------------------------------------------
Example 2
----------------------------------------------------
// Get one row from the database..
$user = $db->get_row("SELECT name,email FROM users WHERE id = 2");
echo $user->name;
echo $user->email;
You are issuing a statement that is specifically to fetch one single row.
What you want to use is get_results() method instead of get_row() method.
I re-read your question and see that you were doing limit 0,100 which returns 100 rows starting with 0 (first). i thought you were trying to cycle those rows but I can see you are actually trying to only get the last row... my bad, derp.. well here - you are reversed somewhat in your query - should be 100,1 as you want the 100th row and only 1 row.
$last = $db->get_row("select * from data where name='{$s}' order by id desc limit 100,1");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
Since you are trying to get last 100 rows use following statement:
$last = $db->get_results("select * from data where name='$s' order by id desc limit 100");
instead of
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
ezSql get_results is the method which you need to use for retrieving multiple results from database.

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

PHP postgresql select, getting id of the one that follows the current one

I am getting 10 rows with the highest ID from a table ...
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 10");
... then I build 10 divs in a while loop:
while ($row = pg_fetch_row($result)) {
// building divs here
}
BUT I want to also include the name that belongs to the next w_news_id in that same div (as a "teaser" for the "next"-arrow). So I was thinking I have to run a second query with the ID that would be next in the loop.
How is the SQL syntax for that? Or is there maybe a better way to do this?
You can use the lead window function:
SELECT w_news_id, name, w_newsnachricht, w_newsdatum,
LEAD (name) OVER (ORDER BY w_news_id) AS next_name
FROM adempiere.w_news
ORDER BY w_news_id DESC
LIMIT 10
You can select one more record - LIMIT 11, instead of 10, and process it differently in PHP.
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 11");
$i = 0;
while ($row = pg_fetch_row($result) and $i < 10) {
$i++;
// building divs here
}
// then process the arrow and teaser separately (if present)
if ($row = pg_fetch_row($result)) {
// show teaser div
}
UPDATE
The window function solution provided by Mureinik is better.

trying to pull in the 2nd record in this query

I have the following query which i am using to pull in data into an html page. The url is something like example.com/sss.php?eventid=1111. So what the query does is it calls the event id and 1 record > than the event id. How would i call the 1 record > than the event id so i can use it for a next button?
$eventid = _GET['eventid']
$resultnext = mysql_query("SELECT tblimage.*, events.*
FROM events LEFT JOIN tblimage ON events.id_user = tblimage.userid
WHERE event_id >= '$eventid'
Order By event_id DESC
LIMIT 2")
The way you have it now if you have the following eventids: 1111, 1112, 1113, 1114, 1115, 1116, 1117. With your query it would return 1116 and 1117. So, I think all you may need to do is change the DESC to ASC. Doing so should produce 1111 and 1112.
EDIT, if you only need the next record for the button then use LIMIT 1 and something like the following:
$eventid = _GET['eventid']
$resultnext = mysql_query("SELECT events.*, tblimage.*
FROM events LEFT JOIN tblimage
ON events.id_user = tblimage.userid
WHERE event_id > '$eventid'
Order By event_id
LIMIT 1");
$nResults = mysql_num_rows($resultnext);
if ($nResults > 0) {
$row = mysql_fetch_row($resultnext);
echo $row[0]; // 1112 would be what is returned if event id was the first field
echo $row[1]; // would be what ever the second field is
<a class="ui-pagination-next"
id="next"
data-ajax="true"
href="eventviewtester.php?eventid=<?php echo $row[0];?>"
style="display:none;"
></a>
} else {
//No Records were returned
}
I am not a PHP expert. I just put together this code based on a search I did. The echo $row[0] shows you how to get the individual data pieces. Use that in conjunction with the button code.
Change LIMIT 2 to the following:
LIMIT 2, 1

MySQL next previous record issue

this is my script
<?php
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
$id = 1;
}
$random = $conn->query("SELECT * FROM records ORDER BY RAND()");
$row = $random->fetch();
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DSC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
?>
But I have a problem with it. For example i have 4 records in database :
ID String
1 Test-1
2 Test-2
3 Test-3
4 Test-4
the query works fine it gives me the next record but not the id which i put like if i put id=1 returns id 2 or id=2 returns info for id 3 and the result is not accurate. So my question is what should I do id to return correct result not +1. I know it starts to count from 0 and i want to fix that in my script i want to make it to start from 1.
replace this
$id = 1;
by
$id = 0;
or replace this
SELECT * FROM records WHERE id > ?
by
SELECT * FROM records WHERE id >= ?
^--//-will look for id equal to 1 or bigger
why don't you change your query to
EDIT: Query will not work as records are deleted.
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id = ?");
$stmt_1->bindValue(1,$id +1);
$stmt_1->execute();
So you will get the record with the next highest id.
Just a hint to optimize your query.
One further question do you use auto_increment in your table definition. If you do so, you shold keep in mind that this mysql-sequence starts by one to calculate the primary key
Hope it helps

Categories