[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Loop in php

Posted on 2006-04-15
17
Medium Priority
?
249 Views
Last Modified: 2012-06-27
Hi all,

i have table say,

<table border=0>
<tr>
<td>

<table>
<tr>
<td>Name :
//first record for name should come from Mysql database
</td>
</tr>
<td>Age :
//age data from mysql database
</td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td>Name :
//here next record for name should come from Mysql database
</td>
</tr>
<td>Age :
//age data
</td>
</tr>
</table>

</td>
</tr>
</table>


i have about 50 records and i want to show all these recods using table .
how i can do this ?

any help pls
thanks in advance
0
Comment
Question by:qbank
  • 9
  • 4
  • 2
  • +1
17 Comments
 
LVL 1

Author Comment

by:qbank
ID: 16461630
how i can display 2 records in one raw.
likewise second row wil start with 3 and 4th records

0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16461635
Hi qbank,

Are you sure that you want to make a new table for each person?
Any way you want to do it it will not b e too hard.  I'll post an example in a few seconds/

Joe P
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16461648
$sql = "your sql goes here";
$result = mysql_query($sql, $conn); // Where $conn is the result of mysql_connect()
while ($row = mysql_fetch_array($result))
{
  echo "<table><tr><td>Name: $row[name]</td><tr></table>";
  echo "<table><tr><td>Age: $row[age]</td><tr></table>";
}


This assumes that your table has column names `name` and `age`, which are of course gotten through your sql.
And example sql would be:
SELECT name, age FROM table

Joe P
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 16

Expert Comment

by:dr_dedo
ID: 16461916
u want to show two records at the same row i suppose !
here is a solution, it is not the best out there, but, will do it
first, u convert the record set into an array

$con = mysql_connect('localhost','root','');
$con = mysql_select_db('test');
$query= "select * from table1";
$result = mysql_query($query) or die("Couldn't connect");
if (mysql_num_rows($result)){
while ($row[]=mysql_fetch_assoc($result));

//now we will draw the table displaying two records at a row
echo "<table>";
for ($i=0;$i<count($row);$i=$i+2){
 echo "<tr><td>name: {$row[$i]['name']}</td><td>Age: {$row[$i]['age']}</td>";
 if ($i<count($row)){
 echo "<td>name: {$row[$i+1]['name']}</td><td>Age: {$row[$i+1]['age']}</td></tr>";
 }
}
echo "<table>";
}
else
echo "No records found";


hope that helps
0
 
LVL 1

Author Comment

by:qbank
ID: 16463235
Thanks dr_dedo,
it gives exact result wat i wanted but the problem is, if there is no data in db then i shows blank table after dislplay.. how i can avoid blank table

here is my code..


<?php

$db=@mysql_connect ("$db_host", "$db_user", "$db_pass") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ($db_name, $db);

$query="SELECT * from Tblstudent";
$result= mysql_query($query, $db) or die ('Database Error: ' . mysql_error());

if (mysql_num_rows($result)){
      while ($row[]=mysql_fetch_assoc($result));
      for ($i=0;$i<count($row);$i=$i+2){

       //now we will draw the table

        echo "<!-- Products Table -->";
        echo "<table border=0 cellpadding=0 cellspacing=0 align=center>";
        echo "<tr><td colspan=2 height=15 bgcolor="#ffffff"></td></tr>";
        echo "<tr>";

        echo "<td width=558 valign=top align=center>";
        echo "<table border=0 align=center cellpadding=3 cellspacing=1 bgcolor=#EECFA1>";
        echo "<tr valign=middle bgcolor=#EECFA1><td>ID : {$row[$i]['sid']}</td></tr>";
        echo "<tr><td bgcolor=#FFFFFF><img src=images/{$row[$i]['pic']} width=185 height=191></p></td></tr>";
        echo "<tr><td bgcolor=#FFFFFF>Rank: {$row[$i]['rank']}</td></tr>";
        echo "<tr><td bgcolor=#FFFFFF><input name={$row[$i]['sid']} type=checkbox value={$row[$i]['rank']}></td></tr>";
        echo "</table>";
        echo "</td>";

        if ($i<count($row)){

        echo "<td width=558 valign=top align=center>";
        echo "<table border=0 align=center cellpadding=3 cellspacing=1 bgcolor=#EECFA1>";
        echo "<tr valign=middle bgcolor=#EECFA1><td>ID : {$row[$i+1]['sid']}</td></tr>";
        echo "<tr><td bgcolor=#FFFFFF><img src=images/{$row[$i+1]['pic']} width=185 height=191></p></td></tr>";
        echo "<tr><td bgcolor=#FFFFFF>Rank: {$row[$i+1]['rank']}</td></tr>";
        echo "<tr><td bgcolor=#FFFFFF><input name={$row[$i+1]['sid']} type=checkbox value={$row[$i+1]['rank']}></td></tr>";
        echo "</table>";
        echo "</td>";

        }
      }
        echo "</tr>";
        echo "</table>";
        echo "<!-- /Products Table -->";
}

else
      echo "No records found";

?>

0
 
LVL 1

Author Comment

by:qbank
ID: 16463321
at the bottom it shows blank row with default values like....

ID:     // and blank space
//blank space for picture
Rank:    // and blank space
0
 
LVL 16

Accepted Solution

by:
dr_dedo earned 1000 total points
ID: 16463639
yes, u got a point, but look, here is a more optimized code that would better and consume less resources (if u have a huge resultset)

<?
$con = mysql_connect('localhost','root','pass');
$con = mysql_select_db('test');
$query= "select * from table1";
$result = mysql_query($query) or die("Couldn't connect");
if (mysql_num_rows($result)){
echo "<table>";
while ($row=mysql_fetch_assoc($result)){

//now we will draw the table displaying two records at a row

 echo "<tr><td>name: {$row['name']}</td><td>Age: {$row['Address']}</td>";
 if ($row=mysql_fetch_assoc($result)){
 echo "<td>name: {$row['name']}</td><td>Age: {$row['Address']}</td></tr>";
 }
}
echo "<table>";
}

else
echo "No records found";

?>


this code should work fine and not print the extra blank cells, please keep me informed about its efficacy
0
 
LVL 1

Author Comment

by:qbank
ID: 16464083
perfact result. thanks

is it possible to divide 50 records into 5 pages ? because 50 records in a page is taking much time to load.
is it possible to do paging ?
0
 
LVL 1

Author Comment

by:qbank
ID: 16464088
i increase the points
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16464192
here is a post in ee that explains pagination you asked for

http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21800048.html

if u didn't get it, let me know
0
 
LVL 1

Author Comment

by:qbank
ID: 16465276
thanks dr,
i dont understand how i can apply that code to my above code. any help pls ?
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16466056
this is the same code in the link i gave u, but with a modification to show two records per row

<html>
<head>
<title>Implementing Paging with next and prev</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php
include '../library/config.php';
include '../library/opendb.php';

// how many rows to show per page
$rowsPerPage = 20;

// by default we show first page
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

$query  = "SELECT * FROM table1 LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');

while($row = mysql_fetch_array($result)) {
//now we will draw the table displaying two records at a row

 echo "<tr><td>name: {$row['name']}</td><td>Age: {$row['Address']}</td>";
 if ($row=mysql_fetch_assoc($result)){
 echo "<td>name: {$row['name']}</td><td>Age: {$row['Address']}</td></tr>";
 }
}
echo "<table>";
 
echo '<br>';

// how many rows we have in database
$query   = "SELECT COUNT(val) AS numrows FROM table1";
$result  = mysql_query($query) or die('Error, query failed');
$row     = mysql_fetch_array($result);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{
    if ($page == $pageNum)
    {
        $nav .= " $page ";   // no need to create a link to current page
    }
    else
    {
        $nav .= " <a href=\"$self?page=$page\">$page</a> ";
    }        
}

// creating previous and next link
// plus the link to go straight to
// the first and last page

if ($pageNum > 1)
{
    $page = $pageNum - 1;
    $prev = " <a href=\"$self?page=$page\">[Prev]</a> ";
     
    $first = " <a href=\"$self?page=1\">[First Page]</a> ";
}  
else
{
    $prev  = '&nbsp;'; // we're on page one, don't print previous link
    $first = '&nbsp;'; // nor the first page link
}

if ($pageNum < $maxPage)
{
    $page = $pageNum + 1;
    $next = " <a href=\"$self?page=$page\">[Next]</a> ";
     
    $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
}  
else
{
    $next = '&nbsp;'; // we're on the last page, don't print next link
    $last = '&nbsp;'; // nor the last page link
}

// print the navigation link
echo $first . $prev . $nav . $next . $last;

// and close the database connection
include '../library/closedb.php';
?>
</body>
</html>
0
 
LVL 1

Author Comment

by:qbank
ID: 16467406
thanks but i used this way. pagination code from other site: but i have a problem here pls see how do i fix it.
ofcourse it gives me exact result but page number has some problems

here is the full code:

$page_name=$_SERVER['PHP_SELF'];

if(!isset($start)) {
      // This variable is set to zero for the first page
      $start = 0;
}

$eu = ($start -0);
$limit = 2;
// No of records to be shown per page.
$this = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;

            <?php

            $db=@mysql_connect ("$db_host", "$db_user", "$db_pass") or die ('I cannot connect to the database because: ' . mysql_error());
            mysql_select_db ($db_name, $db);

            /////////////// WE have to find out the number of records in our table. We will use this to break the pages///////
            $query2=" SELECT * FROM TblProducts WHERE product='Accessories'  ";
            $result2=mysql_query($query2, $db) or die('Error, query failed');
            $nume=mysql_num_rows($result2);
            /////// The variable nume above will store the total number of records in the table////

            $query="SELECT * from TblProducts WHERE product='Accessories' LIMIT $eu, $limit ";
            $result= mysql_query($query, $db) or die ('Database Error: ' . mysql_error());

            if (mysql_num_rows($result)){
                  while ($row=mysql_fetch_assoc($result)){
                  //while($noticia = mysql_fetch_array($result))

//now we will draw the table displaying two records at a row

 echo "<tr><td>name: {$row['name']}</td><td>Age: {$row['Address']}</td>";
 if ($row=mysql_fetch_assoc($result)){
 echo "<td>name: {$row['name']}</td><td>Age: {$row['Address']}</td></tr>";
 }
}
echo "<table>";
}

else
echo "No records found";
            ///// Variables set for advance paging///////////
            $p_limit=8; // This should be more than $limit and set to a value for which links to be breaked
            if(!isset($p_f)){$p_f=0;}
            $p_fwd=$p_f+$p_limit;
            $p_back=$p_f-$p_limit;
            //////////// End of variables for advance paging ///////////////

            /////////////// Start the buttom links with Prev and next link with page numbers /////////////////
            echo "<table align = 'center' width='50%'><tr><td  align='left' width='20%'>";
            if($p_f<>0){
                  print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>PREV $p_limit</font></a>";
            }
            echo "</td><td  align='left' width='10%'>";

            //// if our variable $back is equal to 0 or more then only we will display the link to move back ////////
            if($back >=0 and ($back >=$p_f)) {
                  print "<a href='$page_name?start=$back&p_f=$p_f'><font face='Verdana' size='2'>PREV</font></a>";
            }

            //////////////// Let us display the page links at  center. We will not display the current page as a link ///////////
            echo "</td><td align=center width='30%'>";
            for($i=$p_f;$i < $nume and $i<($p_f+$p_limit);$i=$i+$limit){
                  if($i <> $eu){
                        $i2=$i+$p_f;
                        echo " <a href='$page_name?start=$i&p_f=$p_f'><font face='Verdana' size='2'>$i</font></a> ";
                  }
            else {
                  echo "<font face='Verdana' size='4' color=red>$i</font>";
            }
            /// Current page is not displayed as link and given font color red

            }

            echo "</td><td  align='right' width='10%'>";

            ///////////// If we are not in the last page then Next link will be displayed. Here we check that /////
            if($this < $nume and $this <($p_f+$p_limit)) {
                  print "<a href='$page_name?start=$next&p_f=$p_f'><font face='Verdana' size='2'>NEXT</font></a>";
            }
            echo "</td><td  align='right' width='20%'>";
            if($p_fwd < $nume){
                  print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>NEXT $p_limit</font></a>";
            }
            echo "</td></tr></table>";

            ?>


this works fine but in the middle page number is shown like:  0 2 4 6 (it show records instead of page number)
i want to display the page number like 1 2 3 4......n

any help pls



0
 
LVL 2

Expert Comment

by:dKasipovic
ID: 16467667
change

 if($p_f<>0){
               print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>PREV $p_limit</font></a>";
          }
to

if($p_f<>0){
              $brp=($p_limit/$limit)+1;
              print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>$brp</font></a>";
          }

and change

if($p_fwd < $nume){
               print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>NEXT $p_limit</font></a>";
          }

to

if($p_fwd < $nume){
               $brf=($p_limit/$limit)+1;
               print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>$brf</font></a>";
          }
0
 
LVL 1

Author Comment

by:qbank
ID: 16467733
thanks for your reply,
but no effect of these changes.  stil it shows same result like 0 2 4....n  but not 1 2 3...n
0
 
LVL 2

Assisted Solution

by:dKasipovic
dKasipovic earned 200 total points
ID: 16467859
no surprise, that was answer on first view :)

so, after more detailed code reviews I found that solution to your problem probably is

replacing

//////////////// Let us display the page links at  center. We will not display the current page as a link ///////////
          echo "</td><td align=center width='30%'>";
          for($i=$p_f;$i < $nume and $i<($p_f+$p_limit);$i=$i+$limit){
               if($i <> $eu){
                    $i2=$i+$p_f;
                    echo " <a href='$page_name?start=$i&p_f=$p_f'><font face='Verdana' size='2'>$i</font></a> ";
               }
          else {
               echo "<font face='Verdana' size='4' color=red>$i</font>";
          }

with

//////////////// Let us display the page links at  center. We will not display the current page as a link ///////////
          echo "</td><td align=center width='30%'>";
          for($i=$p_f;$i < $nume and $i<($p_f+$p_limit);$i=$i+$limit){
               if($i <> $eu){
                    $i2=$i+$p_f;
                    $br=($i/$limit)+1;
                    echo " <a href='$page_name?start=$i&p_f=$p_f'><font face='Verdana' size='2'>$br</font></a> ";
               }
          else {
               $br=($i/$limit)+1;
               echo "<font face='Verdana' size='4' color=red>$br</font>";
          }

changes I mentioned before do not need to be done. Just those. Then it will show page numbers. I tested it.

Hope I helped. Sorry for the incorrect answer up there.
0
 
LVL 1

Author Comment

by:qbank
ID: 16471292
thanks it works. thanks so much:)
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month19 days, 2 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question