How to Limit the lines my Php List is showing - php

I have a submit form that displays into a list format and I'm wondering what I can do to make it so that the list only displays a certain number of the most current submitted info. I'm testing it and currently the list is on a page and just displays 50+ submissions stretching out the page very long.
<?php
$query='select * from article order by `article`.`time` DESC';
$result=mysql_query($query);
echo '<table width="600px">';
while($row = mysql_fetch_array($result))
{
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
echo '<table>';
?>

Welcome to SO! Modify your sql statement as follows:
$query='SELECT * FROM article ORDER BY `article`.`time` DESC LIMIT 10';
Change 10 to however many entries should be displayed.

Even though you only should select the data you need, you might want to take a look at a for-loop, which is useful if you know how many times you want to run something. You might end up with a loop which looks like this:
for($i = 0; $i < 10 && $row = mysql_fetch_array($result); $i++) {
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
This code runs 10 times IF you have enough data.

Related

Mysql and PHP leaderboard acting strange

I am trying to make a leaderboard and sort my data by kills, but when I try to make it so it only grabs name, kill, death it doesnt grab anything but when I have it grab it all it works. Anyone know why? Code is below please assist.
<?php
$query = $koneksi->prepare("SELECT * from `player`");
$query->execute();
if($query->rowCount() == 0)
I am grabbing my mysql data here, if I change the * to the data I need no data is displayed.
echo "<tr><td colspan='6'><small>There's no player on ban list</small></td></tr>";
}
while($data = $query->fetch())
{
echo "<tr><td>".$data['name']."</td>";
echo "<td>".$data['kill']."</td>";
echo "<td>".$data['death']."</td>";
$kd = $data['kill'] / $data['death'];
echo "<td>".$kd."</td></tr>";
}
?>
Is it something to do with this or is something wrong? I am really confused.
Here you have to use bind_result() and in that you have to pass the number of parameters which is equal to your number of field from your player table.
Because here you are fetching data using select * query.

limited number of rows in a page

Hi I'm retrieving my data from DB
my data is (pic & name ) when I retrieved them I put them in 4 columns
now I wanna limit the number of rows in each page , I want each page shows three rows only
and if there is more data I want to make it display in next page
my code :
<?php
$items_in_row = 4 ;
$index = 0 ;
?>
<table>
<tr>
<?php
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)){
$index++ ; ?>
<td>
<p>
<img id='g1' src='/<?php echo $row["img"] ;?>' width=130 height=130 onClick='f1()'>
</p>
<p> Name: <?php echo $row['name'] ; ?> </p>
<br>
</td>
<?php if ($index%$items_in_row == 0){ ?>
</tr>
<tr>
<?php }
} ?>
</tr>
</table>
One way to do this is to use the LIMIT() function in SQL, passing in variables that you are storing in the session in PHP. Let's say you want 3 rows of 4 pictures on each page, then you want 12 pictures. So you do something like
select * from pictures LIMIT(0,12)
This returns the first 12 items.
You can do it by just tracking page number. Maybe you have a $page variable in your PHP. If you are on page 2, $page contains 2. Use that to construct a dynamic SQL query with your PHP maybe like this...
$sqlQueryStatement = "select * from pictures LIMIT(". ($page-1)*12 . ", 12)";
What this does is for page 2, it produces the sql statement:
select * from pictures LIMIT(12,12)
See how that works? Now you execute that SQL, and you have the set of results that should be output for page 2.
You can use some further logic to take these basic concepts and run with them...extending them to uses like creating the clickable pagination numbers on the bottom of your results and so forth.
i develop my pagination jobs using the following algorithm:
...1) selecting the results
$page = 1; // what page to show, if you dont know 1 is default.
$maxthingsperpage = 5; // how many things (etc. what you show) per page
$offset = ($page * $maxthingsperpage) - $maxthingsperpage; // db id to start reading
$result = mysql_query("SELECT * FROM things LIMIT ".$offset.",".$maxthingsperpage);
...2) display the things into page
$numrows = mysql_num_rows($result);
$numthingstodisplay = ($numrows > $maxthingsperpage ? $maxthingsperpage : $numrows);
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)) {
... display here without worrying about when to break; num rows are exact
}
you can replace $maxthingsperpage with your $items_in_row

php count grouped values

I have searched around and have found many solutions to my question, but I am still having one problem. I am trying to create a table that will have four images per row. This has been done. I have told the script to group by rewardid and it does that so now duplicate images do not appear (the steps to do these I have found on the site). What I am having problems with is that I m trying to put a multiplier under each image to count how many was in each group. (i.e. Lets say I have 5 medals. On my page, it only shows one medal, but I really have 5, so I would like for it to say x5 below the image.) This is what I have so far:
print "<div class='style1'><br> <br><h2>User Medals</div></h3><br />
<table width='80%' class='table' border='0' cellspacing='1'><tr bgcolor='gray'><th></th><th></th><th></th><th></th></tr>";
$result=mysql_query("SELECT * FROM awardsearned WHERE userid=$userid group by rewardid");
$count = 0;
while($res=mysql_fetch_array($result))
{
$award = $res['rewardpic'];
$award2 = $res['rewardid'];
$result2=mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$count2 = count($result2);
if($count==4) //three images per row
{
print "</tr>";
$count = 0;
}
if($count==0)
print "<tr>";
print "<td>";
print "<center><img src='$award' width='100' height='100'/><br />x$count2</center> ";
$count++;
print "</td>";
}
if($count>0)
print "</tr>";
print "
</table>";
Sorry if this is messed up, never posted here before. Here it is on pastebin if needed http://pastebin.com/iAyuAAzV
Update your query like this:
SELECT *,COUNT(rewardid) no_of_rewards
FROM awardsearned WHERE userid=$userid group by rewardid
$res['no_of_rewards'] will hold your number.
This will also eliminate the need for the second query.
These things are called "aggregate functions". More in the documentation.
To answer your question:
The value of $result2 would only give TRUE(1) or FALSE(0). If your query executed correctly $count2 will return 1, therefore you always get 1 in your code.
Try and change
$result2=mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$count2 = count($result2);
TO:
$result = mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$arr = mysql_fetch_array($result);
$count2 = count($arr);
This should give you the actual numbes of records from the resultset.
There are better ways of doing this (look at Bart Friederichs answer!) , like doing only SELECT and loop through resultset once. This would be for performance and for flexibility.
Also take in my consideration that mysql_query is deprecated now, and should not be used. (The preferal methods are to use PDO or mysqli instead)

bad planing with mysql_fetch_assoc?

I am making a page where people can make posts. All of those posts are then shown in a table of 24 cells. I can have the last 24 posts shown with no problem, but now I don't know how to show the prior group(s) of posts. How can I fix my code to do that? I actually have this:
(I'm removing lines to make it easy to read)
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC";
// ---check everything is fine---- //
function retrieve_info($result)
{
if($row = mysql_fetch_assoc($result))
{echo $topic_if; echo $topic_subject; //and what I want in every cell
}
}
<table width="100%" height="751" >
<tr><td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td></tr>
<!-- repeat a few more times :-) -->
</table>
I though that by changing the variable $row with a number before the if statement would alter the output, but I still see the same data printed on screen. What should I do to be able to show next group of posts?
Thanks!!!
At some point when you have hundreds or thousands of records, you are going to want to paginate the results and not just select all records from the table.
To do this you will run one query per 24 records, your sql would be more like this:
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC
LIMIT 0, 24
";
and for the next 24,
LIMIT 24, 24
then
LIMIT 48, 24
and so on.
You would then make next/previous buttons to click which would refresh the page and dispay the next 24, or you would get the next results with an AJAX request and append the next 24 through the DOM.
This suggests having to take a slightly different approach then calling the same function from each table cell.
More like get the relevant 24 results based on the page number you are on, then loop through the results array and print out the table code with values inside it. Based on if the iterator of the loop is divisible by 4 (looks like your grid is 4x6), you print out new tags for the new row, and that sort of thing.
Search around a bit for pagination in php and mysql to get a sense of how this all fits together.
function retrieve_info($result)
{
while($row = mysql_fetch_assoc($result))
{
$topic_id = htmlspecialchars($row['topic_id']);
$topic_subject = htmlspecialchars($row['topic_subject']);
echo '<td>';
echo $topic_if;
echo $topic_subject; //and what I want in every cell
echo '</td>';
}
}

Displaying results after MySQL JOIN query with PHP

$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}

Categories