Fetching last 100 row from mysql not working | JSON fromat - php

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.

Related

How to paginate sql query result?

I have some PHP code, which returns all records from my database. I need 10 results on each page. How to paginate the results? Dunno how to write a piece of code responsible for displaying page numbers...
<?php
$query = $link->query("SELECT * FROM news WHERE category='rhythmix' ORDER BY subject DESC");
while($output = $query->fetch_assoc()){
$text = $output['news'];
$text = str_replace('[video]','<div class="video-container">',$text);
$text = str_replace('[/video]','</div>',$text);
$text = str_replace('[media]','<center>',$text);
$text = str_replace('[/media]','</center>',$text);
$embera = new \Embera\Embera();
echo $embera->autoEmbed($text);
}
?>
Add LIMIT to your query in this way:
SELECT *
FROM news
WHERE category='rhythmix'
ORDER BY subject DESC
LIMIT 0, 10;
The first number (0) is the start position on the resulset and the second one (10) is how many results you want to show (the offset).
To show the second page:
...LIMIT 10, 10
If you always want to show 10 results you just need to to add 10 to the first number of the LIMIT.
Change your query to read
$query = $link->query("SELECT * FROM news WHERE category='rhythmix' ORDER BY subject DESC LIMIT 0, 10");
To display the first 10 rows. The next set of 10 rows can be shown using
...LIMIT 10, 10");
and so on. . .

MySQL SELECT WHERE id IN() get num_rows

I use this code to show category from database
$select_newscats = $mysqli->query("SELECT * FROM news_cats order by ord_show asc");
while ($rows_newscats = $select_newscats->fetch_array(MYSQL_ASSOC)){
$id_newscats = $rows_newscats ['id'];
$title_newscats = $rows_newscats ['title'];
$ord_show_newscats = $rows_newscats ['ord_show'];
$icon_newscats = $rows_newscats ['icon'];
$kind_newscats = $rows_newscats ['kind'];
$description_newscats = $rows_newscats ['description'];
//here is my data
}
i have in news table row for categoies it's name is cats and i insert data inside it like that 1,5,6,8
and i use this code to count news inside each cat
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
it gets only first value for example if i have this values 1,5,6,8 it gets only 1 the first value
I would do the counting in a single sql call, not with php logic and separate sql calls. For this I would join the 2 tables using left join and use a join condition instead of an in clause:
SELECT nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description, count(n.id) as newsnum
FROM news_cats nc
LEFT JOIN news n ON nc.id=n.cats
GROUP BY nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description
ORDER BY nc.ord_show asc
Obviously, make sure that the join condition is the right one. When you loop through the resultset, the number of news per category will be in the newsnum field.
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
Here $rows_newsnum will only return the first row in the database.
Fetch Array only returns one row at a time, and then moves the row pointer forward. For example the following code on the dataset you provided (1, 5, 6, 8).
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 1
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 5
What you need to do is move it into a while loop (like your first example) to get to access each row, like below:
while($row = $select_newsnum->fetch_array(MYSQL_ASSOC)) {
echo $rows_newsnum["id"] . ", ";
}
// Will produce:
// 1, 5, 6, 8,
If you just want to get a count
Your existing code should work fine. And you can omit the call to fetch_array.
$num_newsnum = $select_newsnum->num_rows;
echo $num_newsnum; // Will display 4
Read more about fetch_array on the PHP documentation:
http://php.net/manual/en/mysqli-result.fetch-array.php
Hope this helps.

Get the last row of result set in Laravel query

I have this query in laravel
$listings = DB::select('select auction.*, product.* from auction as auction inner join
product as product on auction.productID=product.id where auction.sold=0 and auction.endDate != NOW() order by auction.created_at desc limit 10');
Now I want to get the id on the last row or the 10th row of the result set $listings. How could I do that?
I couldn't use this kind of code $lastID = Auction::orderby('created_at','desc')->first() because it fetches the last row from the table and not from the result set.
You may try this to get the last record from the result set:
$listings = DB::select('select auction.*, ... limit 10');
$last = end($listings);
Now get the id:
$id = $last->id;

Retrieve data from MySQL skipping first 4 ouputs where it's ORDER by id

I apologize if the title is confusing, it's hard to title this question.
I've been wondering how I could retrieve data from MySQL but only retrieve data skipping first 4 outputs where it's ordered by id.
Ex:
function firstFour()
{
$sth = $this->db->prepare("SELECT data FROM table WHERE category = 'Sports'
ORDER BY id LIMIT 4");
$sth->execute();
$row = $sth->fetch();
return $row;
}
then on the second query, skip the first four where it's ordered by id on the firstFour query above and output the rest of the data from the sports category.
You need to put limit like follows
LIMIT 4 , 4
LIMIT 8 , 4
so on
Use this query, your limit 4 is making it start from row 0 and retrieve up to row 4, setting the limit as 4, xxxx will go from 4 to whatever xxxx is. I used a large number in place of xxxx
"SELECT data FROM table WHERE category = 'Sports'
ORDER BY id LIMIT 4, 99999999999"
To expand on Zahidul's answer and to make your life easier, you might want to generalize your function a little bit - using firstFour(), secondFour(), etc. is going to make your life a lot harder. I would advise taking Zahidul's idea and passing in your limit variable:
function anyFour($lowLimit)
{
$sth = $this->db->prepare("SELECT data FROM table WHERE category = 'Sports'
ORDER BY id LIMIT $lowLimit, 4");
$sth->execute();
$row = $sth->fetch();
return $row;
}
Then if you wanted to keep the function firstFour(), it would be:
function firstFour()
{
return anyFour(0);
}
From there, you could create a simple loop that incremented by 4.
for ($x = 0; $x < 999;$x++) // 999 should be the total number of sets you want to return...
{
// on each loop, $myRows returns the next 4 rows:
$lowLimit = $x * 4;
$myRows = anyFour($lowLimit);
}
Try this:
$sth = $this->db->prepare("SELECT data FROM table WHERE category = 'Sports'
ORDER BY id;");
$sth->execute();
$row = $sth->fetch();
$row_num = 0;
while ($row) {
$row_num +=1;
if ($row_num > 4) {
//do whatever
}
}

How to "shift" query result one row further

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'];
}

Categories