Loop in php

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
LVL 1
qbankAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

qbankAuthor Commented:
how i can display 2 records in one raw.
likewise second row wil start with 3 and 4th records

0
BogoJokerCommented:
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
BogoJokerCommented:
$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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

dr_dedoCommented:
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
qbankAuthor Commented:
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
qbankAuthor Commented:
at the bottom it shows blank row with default values like....

ID:     // and blank space
//blank space for picture
Rank:    // and blank space
0
dr_dedoCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
qbankAuthor Commented:
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
qbankAuthor Commented:
i increase the points
0
dr_dedoCommented:
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
qbankAuthor Commented:
thanks dr,
i dont understand how i can apply that code to my above code. any help pls ?
0
dr_dedoCommented:
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
qbankAuthor Commented:
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
dKasipovicCommented:
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
qbankAuthor Commented:
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
dKasipovicCommented:
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
qbankAuthor Commented:
thanks it works. thanks so much:)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.