Count rows in database and echo out desired row number - php

If I have 5 rows in my mysql database with ids of 2, 4, 5, 6 and 8 and I echo out id 5 how do I then echo out the row number which of course would be row 3? I get row 3 by counting all the rows from the start of the database to the row I am after.

Try to use
SELECT #row_num:=#row_num+1 as row_number, id from table inner join (select #row_num:=0) as temp
$pdo = new PDO(....);
$result = $pdo->query($sql)->fetchAll();
foreach($result as $row) {
print_r($row);
}

The correct solution would be to add some auto_increment key to your table, then each row would have assigned a sequential number. Otherwise you are not guaranteed to get the same number for each id because SQL query without ORDER BY clause is not guaranteed to have any order (i.e. ids may be returned in random order).
Otherwise, the solution given by Andrej L is the correct one.

Couldn't you just count the number of rows before this in the sort order you're using?
COUNT(*) FROM table WHERE id < ?
In this case only rows with id 2 and 3 would count, so the result is 2. If you're using a 1-based index, add one to that and you have your answer.

Related

How select next row pagination in sql

I'm sorry I'm weak for English.
i echo 2 row in each page . how echo next 2 row
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category
WHERE mzmx_post.id = mzmx_post_category.post_id AND zmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2
You can use the two-arguments form of LIMIT to offset the result by a given number of rows, like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2, 2 -- fetch records 3 and 4
This gives you the second page. If you want the third page, then:
LIMIT 4, 2
And so on.
Note that I modified your query so the joining condition between the tables is placed in the ON clause of the join rather than in the WHERE clause.
Better add one extra column (e.g. mzmx_post_key bigint) of Long type in each table and have sequential value on that column. Use that column to fetch data from DB from page wise.
sqL suery should look like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5 and mzmx_post_key> ##last record key##
ORDER BY mzmx_post_key ASC
LIMIT 2
The basic idea is to use
LIMIT n,o
where n is the results per page
o is the offset from the first result
for the p-th page the offset would be
o = p * n
where p = 0,1,2,....

how to retrieve all rows from a table starting from the n'th row

I want to retrieve all rows from a table starting from the n'th row.
For example, if the table has 20 rows and n=9, I want to retrieve all elements Where the first part of the retrieved elements are the elements from 9 to 20 and the second part are form 1 to 8.
[9,10,...,19,20,1,2,...,7,8].
At first,I thought that I can use 2 queries to do that using LIMIT and OFFSET .
//retrieve the 2nd group
SELECT * FROM Tname WHERE 1 LIMIT (Tsize-n+1) OFFSET (n)
//retrieve the 1st group
SELECT * FROM Tname WHERE 1 LIMIT (n-1)
Where I calculate Tsize-n+1, n and n-1 before, and after retrieving elements I combine the two arrays.
But I don't think that this is the optimal solution (I don't want to use more than one query. and calculating the number of elements in the table is consuming).
Is there a better way to do that?
I have a simple idea. Just select all rows, then read first n rows and finally read remaining rows to the end. Just that!
You can also try this :
(SELECT * FROM Tname WHERE id >= n)
UNION (SELECT * FROM Tname WHERE id < n)
You can use small trick to do this:
SELECT * FROM Tname ORDER BY id >= n DESC, id ASC
This way you have results in that order [9,10,...,19,20,1,2,...,7,8].
If that didn't work (you don't know what id must be used as boundary) you can rearrange results in PHP:
$n = 9;
$resultsArray = array_merge(
array_slice($resultsArray, $n),
array_slice($resultsArray, 0, $n)
);
just reverse order by any column and pass the offset and limit
$data = SELECT * FROM table;
in php
krsort($data);
$chunked_data = array_chunk($data,9);

Query To Select Row With Specific ID For Each Of Two Unique Fields & Count Position Of Third Field

My relevant table structure is like so (with id being primary key and having autoincrement):
id | pid | type | distance | pspeed
Each pid (player id) has a unique row for every type and pspeed combination. For example, there is no row with a specific pid value, a specific type value, and more than one pspeed value. Likewise for pid and pspeed, there is not more than one row with the same type value.
My goal is to, for every type (there are 26 total), group by pspeed (there are 7 different pspeed values) and sort by distance descending until a specific pid value is found and return that row with the "rank" or "position" of that row. Basically I want to do a ORDER BY distance for each type and pspeed until a specific pid value is reached.
Is this possible via pure queries? I know how to do this with several queries and loops in a PHP script but I would like to be able to minimize the code I have to write. Unfortunately, I'm quite positive it would require SQL knowledge that is beyond me.
If counting up until a specific pid value is not possible I can just bake that into my PHP script to determine the "rank".
Edit: here is how I'm currently doing this (using CodeIgniter):
$res = array();
$q1 = $this->db1->get_where('uq_players', array('authid' => $authid), 1);
if($q1->num_rows()){
foreach($this->jtype as $type => $value){
foreach($this->pspeed as $speed){
$i = 0;
$this->db1->order_by('distance', 'desc');
$q2 = $this->db1->get_where('uq_jumps', array('type' => $type, 'pspeed' => $speed));
foreach($q2->result() as $row){
$i += 1;
if($row->pid === $q1->row()->id){
$res[] = self::create_array($row, $type, $row->wpn, $i);
break;
}
}
}
}
}
And some sample data.
You can first try geting a rowset of all different scores for a given player and all combinations of type and pspeed, then left join all other scores with the same type and pspeed but greater distance. If your player is ranked first for this combination you will get one row with nulls, otherwise you will get number of rows equal to number of players with greater distance, which incremented will give you the players rank.
SELECT t1.type, t1.pspeed, 1+SUM(t2.pid IS NOT NULL) as rank
FROM scores t1
LEFT JOIN scores t2
ON t1.type = t2.type AND t1.pspeed = t2.pspeed AND t1.distance < t2.distance
WHERE t1.pid = 1
GROUP BY t1.type, t1.pspeed
See Sqlfiddle example.

count the number of rows in mysql?

How to count the number of rows in mysql database tables with php?
if have in database 5 rows, they number show like this(bold):
all columns is: 5
1 row1 2 row2 3 row3 4 row4 5
row5
Just use this SQL query:
SELECT COUNT(*) FROM table_name
If you want to know how many rows were returned by another query, you can use the PHP mysql_num_rows function. (You could also just increment a counter for each row you process, but this function is handy if you need to know the number of records prior to enumerating the results.)
How do we count them back together? LIKE: 1 2 3 4 5. i not want use of id in column database
select list_of_fields,#rn:=#rn+1 as row_num
from table,(select #rn:=0) as r order by id
You can use this
$result = $this->db->get(<table_name>);
$num_rows = $result->num_rows();
$num_rows would be the total rows in table_name
Then you can just do this
echo 'The number of rows in table_name is '.$num_rows;
This query should do the trick for you:
SELECT COUNT(*) as count FROM `table`
The result set would be
[count]
-------
5
Assuming you have 5 rows.
In order to manually count each row and display its index (without using ID), I would do something like
$counter = 1;
$stmt = $db->prepare('SELECT `field` FROM `table`');
$stmt->execute();
while($row = $stmt->fetch()) {
echo "<b>{$counter}:</b> {$row['field']}";
$counter++;
}

mysql row counter

I have a mysql table. It has auto increment on the id. but I regularly delete rows so the numbers are all over the place. I need to get the last n rows out, but because of deletions, the common way of using the max of the autoincremented id column doesn't work well...
1 - Is their another way to get the bottom 50?
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT ... ORDER BY id DESC LIMIT 50
SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
EDIT
To pick the last 50, but sort by id ASC
SELECT X.*
FROM ( SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
) X
ORDER BY X.id
1 - First get total row count like
SELECT COUNT(*) AS c FROM ...
then use
SELECT ..... LIMIT [start],[count]
2 - One idea is to use view , or procedure, but this is much more harder and may be used when there is no other way to avoid this
1 - Is their another way to get the bottom 50?
SELECT * FROM table_name ORDER BY record_id DESC LIMIT 50
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT * FROM table_name
1 - Yes but it is ugly afaik, you do a
SELECT whateveryouwant FROM table ORDER BY yourprimarykey DESC LIMIT 50
the you fetch the rows into an array and reverse the array, in php :
$r = mysql_query('SELECT * FROM table ORDER BY primarykey DESC LIMIT 50');
$set = array();
while($row = mysql_fetch_assoc($r)) $set = $row;
$set = array_reverse($set);
foreach($set as $row) {
// display row ...
}
2 - You'll have to manage your primary key by yourself, its a bit risky ...

Categories