bad planing with mysql_fetch_assoc? - php

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>';
}
}

Related

Create a table with blank squares for missing mysql data

I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.

How to display long while/for loop in pagination?

I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?
<table>
<?php $count = 1000;
for($a=1;$a<=$count;$a++) { ?>
<tr>
<td><?php echo $a; ?></td>
<td>This is number <?php echo $a; ?></td>
</tr>
<?php $i++;
} ?>
</table>
My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:
$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
$start = $_GET['record_number'];
$end = $_GET['record_number'] + 1000;
}
for($a=$start; $a<=$end; $a++){
//code here
}
Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.
If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.
SELECT title, description FROM posts LIMIT 25
This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.
SELECT title, description FROM posts LIMIT 25, 50
This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.
I hope this can help you, happy coding!
Update
This is a little tutorial in using the LIMIT clause in MySQL
Here is my example, it's similar to the answer from #AnotherGuy
<form method="GET">
<input type="text" name="rowsPerPage">
<?php
for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
echo '<input type="submit" name="page" value="'.$i.'">';
}
?>
</form>
<?php
$begin = (int)$_GET['rowsPerPage']*$_GET['page'];
$take = (int)$_GET['rowsPerPage'];
$sql = "SELECT ... LIMIT {$begin}, {$take}";
?>
It's possible that the code contains "typos", but I hope it will give you new ideas.
I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.
www.example.com?rowsPerPage=150&page=2

Generating pages based on amount of data returned from MySql Query

im making a review section for my site, and i want to generate pages based on amount of data returned by a MySQL query, something like 15 MySQL Rows pr page, i have tried looking in to the $_GET[pageID] approach, but i simply dont get it.
Could someone please elaborate or give me a suggestion? At the moment i echo Sql results in to a div on a reviews.php page.
What i have at the moment is this:
<?php
$con = mysql_connect("localhost", "cencor","cencor");
if (!$con) {
die('<br /><br />Could not connect: ' . mysql_error());
}
function feedbackList() {
mysql_select_db("cencor") or die(mysql_error());
$localIP = $_SERVER['REMOTE_ADDR']; // get IP
$rows = mysql_query("SELECT * FROM feedback WHERE approved=1 ORDER BY sorting DESC");
while ($row = mysql_fetch_array($rows)) {
echo '
<div id="reviews">
<div id="date">'. $row['date'] . "</div> <div id='time'>" . $row['time'] .'</div>
<h2>'. $row['name'] .'</h2>
<br>
<p>'. $row['feedback'] .'</p>
</div>
';
}
}
?>
time and date are set in another script, so no worries there, this code runs fine
First, get the count of all rows in your table:
SELECT COUNT(*) FROM feedback WHERE approved=1
Now you know how many pages you will have and you can display links to each page.
Query the first page:
SELECT * FROM feedback WHERE approved=1 ORDER BY sorting DESC LIMIT 0, 15
This will give you the first 15 rows from your table. On the next pages you would use:
LIMIT 15, 15
LIMIT 30, 15
LIMIT 45, 15
and so on. Just replace the first LIMIT parameter with the offset of rows you would like to have. Second LIMIT parameter is the number of rows to be returned.
You could return all of the reviews in one SQL statement and then use PHP's array chunks function to split them into multiple arrays. http://php.net/manual/en/function.array-chunk.php You could then store each array on the page as a JS variable and use AJAX, or whatever have you.
You can pass this function an array (all of the reviews) and a number (say 15) and it will output however many possible arrays of length 5. So in your case, if you had 150 reviews in an array and you wanted to limit a page by 15 reviews, this function would return 10 arrays of 15 elements each.
You then just take each array of reviews and represent it as a page.
Alternatively, you can use LIMIT in SQL for each page. You would want something that looks like:
LIMIT 0, 15
LIMIT 15, 15
LIMIT 30, 15
... etc
The first number is what index to start at and the second number is how many results to show.
So you could do something like (15 * (pageNumber - 1)) to get the first number on each page (assuming pageNumber starts at 1).

How to Limit the lines my Php List is showing

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.

How can I display this table correctly?

I am working on a very simple webshop, it should echo different products in a table of 2 <td> by 4 <tr> but now it only displays the different products downwards. Hopefully someone here can help me.
$result=mysql_query("select * from products");
while($row=mysql_fetch_array($result)) {
$artikel = '<div style="background-color:#E3E3E3;width:200px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row['picture']).'"><br><div align="center"><b>'.htmlspecialchars($row['name']).'</b><br><h6>€'.htmlspecialchars($row['price']).'</h6></div></div>';
echo '<table><tr><td>'.$artikel.'</td>';
echo '</table>';
}
Why would it display a table of 2 by 4?
You are putting every product in its own table, so the first thing to do, is move the table tags out of the loop and then you need to add logic to add a new row after every x products.
Although you don't seem to need a table as your div has fixed dimensions, so you can just get rid of the table and use css to get the grid you want.
If this is your entire code then you're missing a tr tag.
Could be a possible cause for your lay-out shifting.
Instead of using breaks, I'd recommend using multiple divs (or table lay-out if you're more comfortable with that) as breaks aren't always handled the same in all browsers.
Instead of creating new table for every records, you can use one row per record.
$result=mysql_query("select * from products");
if(mysql_num_rows($result) > 0){
echo '<table>';
while($row=mysql_fetch_array($result)) {
$artikel = '<div style="background-color:#E3E3E3;width:200px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row['picture']).'"><br><div align="center"><b>'.htmlspecialchars($row['name']).'</b><br><h6>€'.htmlspecialchars($row['price']).'</h6></div></div>';
echo '<tr><td>'.$artikel.'</td></tr>';
}
echo '</table>';
}

Categories