MySQL displaying 1 result within while loop...however theirs actually 2 results? - php

I recently combined 2 queries into 1 (to optimize performance)...1 query for checking the count, and the other for the results, the count is to ensure their is actual results their before proceeding with the loop.
Heres the PHP code:
<?php
$query = 'SELECT id, title, COUNT(id) FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_result($result, 0, 2);
mysql_data_seek($result, 0); //mysql_result resets the internal pointer...
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}
?>
The problem is it now returns 1 result? - when theirs actually 2 results inside (as I've checked via PHPMyAdmin aswell as running the following code - see below), I've narrowed down the problem, its because the COUNT(id) has been combined with the intial results query; that its behaving like this.
Because if I do the following:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
?>
It returns 2 results...
So my question is how do i resolve this but achieve what I'm after?

I would recommend that you remove the COUNT(id) and use the mysql_num_rows() function to check how many rows were returned before trying to loop through them.
Your code could then look like this:
<?php
$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count > 0) {
$i = 0;
while ($output = mysql_fetch_assoc($result)) {
++$i;
//etc..
}
}

COUNT is an aggregate function that typically is used with the GROUP BY clause. I don't believe it is meaningful in the query as you used it.

Related

Why does not the fetch statement have any value after the fetch_all statement?

I want to output the number of myTable and output field1 of myTable in the loop.
However, if I run the following code, only 10 'test : ' will be printed.
If I remove [$rows = $statement->fetchAll(PDO::FETCH_ASSOC);] and change the $count of for() to 10, it works fine, but that is not what I intended.
<?php
$db = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8;", myid, mypw);
$statement = $db->query('select field1 from myTable limit 10');
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = count($rows);
echo "count : $count<br><br>";
for($i = 0; $i < $count; $i++)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo 'test : '.$row['field1'].'<br>';
}
?>
I would like to avoid the following methods to count the number of myTable. Because query statements that look similar are added unnecessarily.
$count = $db->query('SELECT count(*) FROM qudtls_mutter')->fetchColumn();
As the result, from
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
will be associative array, that you will need to count.
You can simply use $statement->rowCount():int that will return count from last query.
Then you can use it mixed with FOR
for ($i=0; $i<$statement->rowCount(); $i++) {
}
For other use, you can go with WHILE
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
}
For use foreach, simply:
foreach ($statment as $row) {
}
$db = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8;", myid, mypw);
$statement = $db->query('select field1 from myTable limit 10');
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
The above will, as it says, fetch All of the ten rows. There will be now no more rows to fetch in your result set. This is to be expected.
Change this:
for ($i = 0; $i < $count; $i++) {
$row = $statement->fetch(PDO::FETCH_ASSOC);
to this:
foreach ($rows as $i => $row) {
to have it work. After the fetchAll you already have all the rows, you do not need to fetch them again, and it will not work if you try to.
If you want to output the whole table, do not fetchAll, but fetch until there is nothing left. Remove the fetchAll, and:
$i = 0;
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$i++;
// This will execute for all rows. It will exit as soon as fetch() returns null at the end of the query.

How to select the maximum value of a column in MySQL

I want to select the maximum value of a column of my table. I'm using PHP and MySQL. This is what I have so far:
$max = "SELECT MAX(Id) FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
echo= $max1;
My debugger is just saying that it is a query returning a 0 boolean value (false). I cannot find a specific answer anywhere on the internet.
You need to fetch the data from the mysqli_result object that was returned to you when you executed your query using mysqli_query.
$max = "SELECT MAX(Id) as id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1); // this was missing
$id=$row['id'];
echo $id;
Note: I removed the loop because with MAX query without any grouping you will get only 1 row returned. If you had multiple rows in result set you would need to loop through all of them
two ways
first is as people described
$max = "SELECT MAX(Id) as max_id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
$max_id=$row['max_id'];
echo $max_id;
second is ordering and limiting
$max_id = 0;
$max = "SELECT id FROM trialtabel2 order by id desc limit 0,1";
$max1 = mysqli_query($dblink, $max);
while($row = mysqli_fetch_assoc($max1)){
$max_id=$row['id'];
}
echo $max_id;
In Your code you missing the fetch statement. you need to fetch from the resultset. see above what you are missing.
Try using this..,
$max = "SELECT MAX(Id) as maxId FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
echo $row['maxId'];
Hope this helps..
$max = "SELECT Id FROM trialtabel2 order by id desc limit 1";
$max1 = mysqli_query($dblink, $max);
$result = mysqli_fetch_assoc($max1);
pre($result);

Limit query results after receiving result

I'm having sort of an issue with sorting and giving sort of a ranking while having pagination.
$query = "SELECT * FROM users WHERE approved=1 ORDER BY Likes DESC LIMIT $start_from, $num_rec_per_page";
$result = mysqli_query($conn,$query);
$i=1;
while($row = mysqli_fetch_assoc($result)){
echo 'Rank: '.$i++.'. Name:'.$row[Name].'Likes: '.$row[Likes].'<br>';
}
This way, every page rank is given all over again.
My question is, how to Limit query only AFTER receiving all data,
or maybe some advice on doing other way of pagionation.
UPDATE:
Fixed the problem by changing $i=1; to $i=$start_from+1;
Limiting the $i ?
$maxPerPage = 20;
$i = 0;
while($i < $maxPerPage && $row = mysqli_fetch_assoc($result)){
echo 'Rank: '.$i++.'. Name:'.$row[Name].'Likes: '.$row[Likes].'<br>';
}
But LIMITING in mysql (in your case) is better than getting all rows and fetching just some.

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

PHP Order by ASC not working on decimal type

Have a quick question regarding ORDER. I have a list of scores I am displaying in a high scores table using php. I need the lowest decimal number to display in 1st place, however when I try to use the ASC command, no results display. But if I use DESC the results do display, but in the opposite order to what I need (lowest decimal displays last).
Here is the "working" code that displays the scores, but in the wrong order.
$query = mysql_query("select reflex,playerID from users_stats order by reflex DESC limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
Here is the code that displays nothing (no results are returned).
$query = mysql_query("select reflex,playerID from users_stats order by reflex ASC limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
I have also tried this (default);
$query = mysql_query("select reflex,playerID from users_stats limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
And again, no results display....
The reflex score is being stored in a MySQL database using decimal(4,3) default None. Can anyone point me in the right direction? I have tried to google it, but can't seem to find anything specific to what I need. I assume it is something to do with decimal??
Thanks in advance.
*EDITED - I do appreciate any answers/advice, however I am very new to php and still desperately trying to learn :/
Probably you have 0 in column "reflex" and line
if ($row[reflex] <= 0) break;
made exit from cycle

Categories