How to display five rows? - php

How can I use PHP to show five rows from a MySQL database, then create a new line and show another five, etc?

Use the LIMIT clause if you want to limit the amount of results returned from the query.
If you want to print an <hr/> after every fifth record you can check it via the modulus operator:
$counter = 1;
while ($row = mysql_fetch_assoc($rst)) {
// print $row stuff
if ($counter % 5 == 0)
print "<hr />";
$counter++;
}
Basically, we have a variable used to count how many records we've printed. Once that counter can be divided by five, and leave no remainder, we print our horizontal-rule.

Something like this may be helpful:
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_assoc($result)) {
if(++$i%5==0 && $i>0) {
/* do the extra thing... new line some styles */
}
}
}

Err.. you mean something like:
SELECT * FROM `tablename` WHERE ... LIMIT 5

$total = 20;//get total number here;
$limit = 5;
for($i = 0;$i< $total/$limit;$i++)
{
$sql = $result = $rows = "";
$start = $limit * $i;
$sql = "select * from m_table order by id desc limit $start,$limit";
$result = mysql_query($query);
while($rows = mysql_fetch_assoc($result))
{
//print the result here;
}
}
You can fetch 5 rows every time from mysql without fetching all the rows at once.

Related

My for loop only allows one post to be displayed, over and over again

/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html

I want to retrieve data from mysql php

$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."'limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
for ($i=0; $i<=mysqli_num_rows($result_importer1); $i++)
{
$row = mysqli_fetch_assoc($result_importer1);
echo ''.$row['item_name'].'<br>';
}
i want all item name but its printing only one
You do not need to execute for loop on records, You can get all records using while loop, Plz refer below code
$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."' limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
while($row = mysqli_fetch_assoc($result_importer1)){
echo $row['item_name'];
}

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 limit with PHP variable

This is my code below
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
$match = 0; //In reality it's an array search function which returns 1 on match
if($match == 1) {
echo"Show content!";
}
}
Im trying to make an list with 10 rows, and i have a function which uses "name" from table to run an search query with an array generated by twitter API. In example if i get 3 matching records, i still want to show a list with 10 rows but hide the matching elements from there.
At the moment the script hides the matching elements and shows 7 rows instead of 10.
That is what i need help with, cheers :)
Process the data you are getting from the twitter api, collect the data you need in an array and query the database afterwards.
Something like that:
<?php
$collectArray = array();
foreach ($twitterData as $index => $data) {
if ($someCriteria === TRUE) {
$collectArray[] = $data;
}
}
$implodedCollectArray = "'" . implode("', '", $collectArray) . "'";
$sql = "SELECT * FROM `table_name` WHERE `some_column` IN (" . $implodedCollectArray . ")";
$query = mysql_query($sql) or die(mysql_error());
while($f = mysql_fetch_array($query)){
echo $f['column'];
}
?>
reinitilize match variable as the code:
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
if($f['name']!='variable_name_twiter'){
$match = 1; //In reality it's an array search function which returns 1 on match
}
if($match == 1) {
echo"Show content!";
}
$match = 0;
}

Creating multiple pages from sql query

I am trying to create multiple pages from my query. If I have 100 results, and I want 10 results per page, I would like there to be ten pages created, with each page showing a different query. This is how my query is set up:
$sql ="SELECT * FROM Post WHERE (active ='1') ORDER BY PostID DESC ";
$result = mysql_query($sql,$db);
$numrows = mysql_num_rows($result);
while(($post = mysql_fetch_assoc($result))) {
$posts[] = $post;
}
<?php
if (!$numrows){ echo $errormessage;}
else{
foreach($posts as $post): ?>
echo stripslashes($post['text']);
<?php endforeach; }?>
This pulls each "post" from the database and puts displays them all out.
I would like to do something like this:
$results = mysql_num_rows($result);
$numpages = 10/$results; //gives the number of pages
while($numpages<$results)
{
//run code from above\\
}
What is the best way to do this with the method that I use? I appreciate your opinions because I'm at one of those stages where I'm lost in my own logic. Thank You!
Most pagination examples fail to meet real life requirements. A custom query string, for example.
So, here is a complete yet concise example:
<?
per_page=10;
// Let's put FROM and WHERE parts of the query into variable
$from_where="FROM Post WHERE active ='1'";
// and get total number of records
$sql = "SELECT count(*) ".$from_where;
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$total_rows = $row[0];
//let's get page number from the query string
if (isset($_GET['page'])) $CUR_PAGE = intval($_GET['page']); else $CUR_PAGE=1;
//and calculate $start variable for the LIMIT clause
$start = abs(($CUR_PAGE-1)*$per_page);
//Let's query database for the actual data
$sql = "SELECT * $from_where ORDER BY PostID DESC LIMIT $start,$per_page";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// and fill an array
while ($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
//now let's form new query string without page variable
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['page']);
if ($tmpget) {
$uri .= http_build_query($tmpget)."&";
}
//now we're getting total pages number and fill an array of links
$num_pages=ceil($total_rows/$per_page);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'page='.$i;
//and, finally, starting output in the template.
?>
Found rows: <b><?=$total_rows?></b><br><br>
<? foreach ($DATA as $i => $row): ?>
<?=$i?>. <?=$row['title']?><br>
<? endforeach ?>
<br>
Pages:
<? foreach ($PAGES as $i => $link): ?>
<? if ($i == $CUR_PAGE): ?>
<b><?=$i?></b>
<? else: ?>
<?=$i?>
<? endif ?>
<? endforeach ?>
It would be hideous to extract all data from the database and manage it from PHP. It would kill the RAM, and the network.
Use the LIMIT clause for paging.
First, you need to see the total number of records. Use
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1';
then,
$result = mysql_query($query, $db);
$row = mysql_fetch_assoc($result);
$count = $row['cnt'];
$pages = ceil($count/10.0); //used to display page links. It's the total number of pages.
$page = 3; //get it from somewhere else, it's the page number.
Then extract the data
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1 LIMIT '.$page*10.', 10';
$result = mysql_query($query, $db);
while($row = mysql_fetch_assoc($result))
{
//display your row
}
Then output the data.
I'm using that similar code to do that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
That code get total rows
and that for creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
You can also read about : pagination

Categories