php, mySQL return last x rows - php

I'm working on a php/mySQL/ajax shoutbox and have run into a small snag.
On the page I want the content to be loaded from oldest to newest, with the newest on the bottom. I also want to limit the output to reduce load times once the database starts to get a lot of data in it.
Here is the current code;
<?php
include_once("../includes/db.php");
include_once("../includes/functions.php");
$q="SELECT tM.*, tC.char_name as username, tC.char_id as char_id
FROM shoutbox tM JOIN characters tC
ON tC.char_id=tM.char_id
ORDER BY shout_id DESC LIMIT 25";
db_Connect();
$result=mysql_query($q);
while($row=mysql_fetch_array($result))
{
$classColor = getClassColor($row['char_id']);
echo "<span class='".$classColor."'>".$row['username']."</span>: ",nl2br($row['shout_message'])."<br />";
}
mysql_Close();
?>
I have tried using while($row=array_reverse(mysql_fetch_array($result))) as well as $result = array_reverse(mysql_query($q)) but both return an error that array_reverse needs to be fed an array.
So far anything I have found on the web from the SQL side have all been answered "just use DESC or ASC accordingly."

$res = mysql_query($q);
$shouts = array();
while($row = mysql_fetch_assoc($res))
$shouts[] = $row;
$shouts = array_reverse($shouts);
foreach($shouts as $shout) {
// show them...
}

If you want oldest to newest, and shout_id is auto increment just use
ORDER BY shout_id ASC LIMIT 25
You have DESC/ASC mixed up

$result=mysql_query($q);
unset($temp_array);
while($row = mysql_fetch_array($result))
$temp_array []= $row;
$temp_array = array_reverse($temp_array);
foreach ($temp_array as $row)
{
$classColor = getClassColor($row['char_id']);
echo "<span class='".$classColor."'>".$row['username']."</span>: ",nl2br($row['shout_message'])."<br />";
}

Seems like a lit of work. I just used this:
$result = mysql_query($strQuery) or die(mysql_error());
while ($row = array_reverse(mysql_fetch_array($result))) {
$row['something'];
}

Related

obtaining comments for each post

hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

MYSQL Order BY "entry" DESC Not showing the highest

i'm having a slight problem with this mysql query.
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$list = mysql_fetch_assoc($result);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
Want i'm wanting to achieve is it listing 5 entrys by order "Counter" But when listing it? it only shows 4 entrys like so :-
5648
4575
1595
35
So where is my 5th entry? and why isn't it posting it? NOTE that the 5th entry is also the highest with a value of
305355
Thanks in advance
You fetch before the loop which pops one record off the result set (i.e. 305355).
$list = mysql_fetch_assoc($result); // REMOVE THIS LINE
while($list = mysql_fetch_assoc($result)) {
// output code
}
Try to reduce the code and use mysqli_ functions
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn);
while($list = mysql_fetch_assoc($result)){
echo $list['counter']."<br>";
}
try out this code..
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
you are calling mysql_fetch_assoc two time that is why your first row get by first time you called the mysql_fetch_assoc and remaining show in second calls

10 random mySQL rows to different lines

Basically, I'm trying to get 10 random rows from MySQL and put them in my page. Getting those 10 random rows is easy.
The code that i have is:
$r = mysql_query("SELECT * FROM email order by rand()limit 10")
or die(mysql_error());
while($row = mysql_fetch_assoc($r))
{
echo $row['Email'];
}
Now, echo gets those 10 rows and shows them to me, but I need to separate them, so I can put them in my site, one per div or whatever. Can anyone tell me how to separate those emails so I can put each of them in the place I need?
$r = mysql_query("SELECT * FROM email order by rand()limit 10")
or die(mysql_error());
while($row = mysql_fetch_assoc($r))
{
echo "<div>";
echo $row['Email'];
echo "</div>";
}
What I would do in this instance would be:
$r = mysql_query("SELECT * FROM email ORDER BY rand() LIMIT 10")
or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($r))
{
$data[] = $row;
}
This will give you a array of random rows, You can then in your HTML do the following:
echo $data[0]['Email'];
Replacing the ID of the array with what random record you want..
No idea why you want to do like that, it is a pretty bad design but however if that is what you want, all you have to do is:
$r = mysql_query("SELECT * FROM email order by rand()limit 10")
or die(mysql_error());
while($row = mysql_fetch_assoc($r))
{
$email[] = $row;
}
now you have an array called $email with 10 elements in it. You can use it so, replacing field_name with whatever your email fields are:
<div><?php echo $email[0]['field_name'];?></div>
<lots of other html tags>
<div><?php echo $email[1]['field_name'];?></div>
<yet again more html tags>
<div><?php echo $email[2]['field_name'];?></div>

in array sql query

I have the following inside a foreach loop (displaying my various videos), I'm trying to display some alternate text for the top three voted videos. What on earth am I doing wrong (a lot clearly)...
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
$row = #mysql_fetch_array($result);
if(in_array($video->getProperty('video_id')) == $row['video_id']) {
do this...
} else {
do this..
}
Firstly replace your code with some error preventing techniques like so!
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
{
$row = mysql_fetch_assoc($result); //Dont need the # restraint as the result is not false above.
//Also to get associate keys you need to use mysql_fetch_assoc
if($video->getProperty('video_id') == $row['video_id'])) //Remove the in array as your directly comparing the to entities with ==
{
//Match
}else
{
//Video does not match
}
}
Your main problem was the mysql_fetch_array(), Please research the differences with mysql_fetch_array() and mysql_fetch_assoc();
--
Edit: The way i would go
//Change the query and the loop way.
$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int)$video->getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
//Use the # restraint if you have E_NOTICE on within E_Reporting
{
while($row = mysql_fetch_assoc($result))
{
//Print the $row here how you wish for it to be displayed
}
}else
{
//We have an error?
echo '<strong>Unable to list top rated videos, please check back later.</strong>'
}
}
mysql_fetch_array only returns a single row, you need to loop through your results to build an array containing the top three ids.
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
while($row = #mysql_fetch_array($result)) {
$topthree[] = $row["video_id"];
}
Then you can use in_array but with the correct syntax:
if(in_array($video->getProperty('video_id'), $topthree)) {
do this...
} else {
do this..
}

Categories