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
Related
I have written a MySql query to get the columns related with minimum id . Looks something like this
SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed=21
The table has 4 rows looks like this
So according to the function that I have written
function setLC()
{
$sql = "
SELECT min(id) as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
";
$result = $this->localDb->execute($sql);
$row=mysql_fetch_array($result);
echo $sql;
echo $row['idpropiedad'];
$this->lastCode = $row['idpropiedad'];
}
It returns empty string for idpropiedad
Can any one help me out where I am going wrong
Thanks in advance
I'd think the query you're actually looking for is this:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE feed = 21
ORDER BY id ASC
LIMIT 1
MIN() is giving you the generally lowest value in the column, it does not affect the rest of the columns. If you want the whole row with the lowest id it doesn't help.
To illustrate, if you really wanted to use MIN here, you'd have to do:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE id = (SELECT MIN(id) FROM registrofeed WHERE feed = 21)
You can do a better query like this:
$sql = "
SELECT id as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
HAVING MIN(id)
";
This will return only one row with the minimum id number. It's more readable than using ORDERING AND LIMIT 1.
try your select query as
SELECT * FROM registrofeed WHERE feed='21' ORDER BY id ASC LIMIT 1
this fetches the row having minimum id.
Hope it helps
Try this
$sql = "SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed='21' order by id asc";
I got a little problem, I've got a database, in that database are different names, id, and coins. I want to show people their rank, so your rank has to be 1 if you have the most coins, and 78172 as example when your number 78172 with coins.
I know I can do something like this:
SELECT `naam` , `coins`
FROM `gebruikers`
ORDER BY `coins` DESC
But how can I get the rank you are, in PHP :S ?
You can use a loop and a counter. The first row from MySql is going the first rank,I.e first in the list.
I presume you want something like:
1st - John Doe
2nd - Jane Doe
..
..
right?
See: http://www.if-not-true-then-false.com/2010/php-1st-2nd-3rd-4th-5th-6th-php-add-ordinal-number-suffix
Helped me a while ago.
You could use a new varariable
$i = "1";
pe care o poti folosi in structura ta foreach,while,for,repeat si o incrementezi mereu.
and you use it in structures like foreach,while,for,repeat and increment it
$i++;
this is the simplest way
No code samples above... so here it is in PHP
// Your SQL query above, with limits, in this case it starts from the 11th ranking (0 is the starting index) up to the 20th
$start = 10; // 0-based index
$page_size = 10;
$stmt = $pdo->query("SELECT `naam` , `coins` FROM `gebruikers` ORDER BY `coins` DESC LIMIT {$start}, {$page_size}");
$data = $stmt->fetchAll();
// In your template or whatever you use to output
foreach ($data as $rank => $row) {
// array index is 0-based, so add 1 and where you wanted to started to get rank
echo ($rank + 1 + $start) . ": {$row['naam']}<br />";
}
Note: I'm too lazy to put in a prepared statement, but please look it up and use prepared statements.
If you have a session table, you would pull the records from that, then use those values to get the coin values, and sort descending.
If we assume your Session table is sessions(session_id int not null auto_increment, user_id int not null, session_time,...) and we assume that only users who are logged in would have a session value, then your SQL would look something like this: (Note:I am assuming that you also have a user_id column on your gebruikers table)
SELECT g.*
FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id
ORDER BY g.coins DESC
You would then use a row iterator to loop through the results and display "1", "2", "3", etc. The short version of which would look like
//Connect to database using whatever method you like, I will assume mysql_connect()
$sql = "SELECT g.* FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id ORDER BY g.coins DESC";
$result = mysql_query($sql,$con); //Where $con is your mysql_connect() variable;
$i = 0;
while($row = mysql_fetch_assoc($result,$con)){
$row['rank'] = $i;
$i++;
//Whatever else you need to do;
}
EDIT
In messing around with a SQLFiddle found at http://sqlfiddle.com/#!2/8faa9/6
I came accross something that works there; I don't know if it will work when given in php, but I figured I would show it to you either way
SET #rank = 0; SELECT *,(#rank := #rank+1) as rank FROM something order by coins DESC
EDIT 2
This works in a php query from a file.
SELECT #rank:=#rank as rank,
g.*
FROM
(SELECT #rank:=0) as z,
gebruikers as g
ORDER BY coins DESC
If you want to get the rank of one specific user, you can do that in mysql directly by counting the number of users that have more coins that the user you want to rank:
SELECT COUNT(*)
FROM `gebruikers`
WHERE `coins` > (SELECT `coins` FROM `gebruikers` WHERE `naam` = :some_name)
(assuming a search by name)
Now the rank will be the count returned + 1.
Or you do SELECT COUNT(*) + 1 in mysql...
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
So I'm trying to add a little bit of convenience to a CRUD by adding next and previous links to navigate between records in my database.
Here are my queries:
$id=$_GET['id'];
$id = $currentid;
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery);
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
?>
Here is my HTML:
Previous
Next
Now I tested these queries in PHPMyAdmin and they produced the result I wanted, but I can't get my hyperlinks to actually be supplied with the correct IDs... they're just blank after the =. What am I doing wrong?
mysql_query() returns a result set (resource). To get the actual rows from the result set, you need to use a function like mysql_fetch_row().
Your code for the "next" link would look something like:
PHP
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
if(mysql_num_rows($nextresult) > 0)
{
$nextrow = mysql_fetch_row($nextresult);
$nextid = $nextrow['id'];
}
HTML
Next
and the previous link would be done similarly.
Obligatory note: For new code, you should seriously consider using PDO.
Advanced note:
You could combine your queries into a single query like:
SELECT
(
SELECT id
FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1
) AS previd,
(
SELECT id
FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1
) AS nextid
And then adjust the logic accordingly.
Okay, It took a little bit but I figured it out...
PHP
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery) or die(mysql_error());
while($prevrow = mysql_fetch_array($prevresult))
{
$previd = $prevrow['id'];
}
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery) or die(mysql_error());
while($nextrow = mysql_fetch_array($nextresult))
{
$nextid = $nextrow['id'];
}
HTML
Previous
Next
Thanks for the help, I think it put me on the right course. I'll look into that PDO stuff for the future. I'm just now starting to get a hang of the old MYSQL/PHP syntax and now all the sudden there's a new format... tough to keep up with it all!
The resultant code has a culprit at the very beginning and end of the table. Your code will "die" as you ordered. Instead you might check the query results ($prevresult, $nextresult) and decide NOT to show a link for previous or next item.
SELECT
IFNULL(
(SELECT id FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1 ) , (SELECT id FROM inventory ORDER BY id DESC LIMIT 1 )
) AS previd ,
IFNULL(
(SELECT id FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1 ),
(SELECT id FROM inventory ORDER BY id ASC LIMIT 1 )
) AS nextid
Each page lists all the coupons available for a specific retailer. I query the database for all the coupon codes in the header since I count the number of rows returned and use that info in the meta title of the page. I now also want to display the titles of the first 2 coupons in the array. How would I go about extracting the first 2 results from the array without querying the database again?
This is what I have so far:
$retailer_coupons = "select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category from tblCoupons C,tblMerchants M where C.merchantid=M.merchantid and C.begin < ".mktime()." and C.expire > ".mktime()." and C.merchantid=".$merchantid." and M.display='1' and C.user_submitted='' order by C.custom_order desc, C.coupon desc";
$retailer_coupons_result = mysql_query($retailer_coupons) or die(mysql_error());
$count_coupons=mysql_num_rows($retailer_coupons_result);
$meta_title = ''.$name.' Coupon Codes ('.$count_coupons.' coupons available)';
Suppose I have 3 records in my table. If I execute below query, I will get 2 results however the count(*) will give me 3 as output
SELECT count(*) FROM temp.maxID limit 2
In your case it will be
$retailer_coupons =
"select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category
from tblCoupons C,tblMerchants M
where C.merchantid=M.merchantid
and C.begin < ".mktime()." and C.expire > ".mktime()."
and C.merchantid=".$merchantid." and M.display='1'
and C.user_submitted=''
order by C.custom_order desc, C.coupon desc
limit 2";
limit 2 will do the magic... Cheers!!!
Good Luck!!!
Something like this:
$res = mysql_fetch_assoc($retailer_coupons_result);
$i = 0;
while ($i < 2){
echo $res[$i]['label']."\n";
$i++;
}