简体   繁体   中英

Output of MySql Data in Two Columns from Right to Left

Output of data records from mySql table is required in two columns starting from right side, ie records 1 & 2 should appear in the second column while 3 & 4 should display in the first column. Both the columns should be able to display any number of records, not just two that is shown here as an example.

mySql table :

1. fname     lname     age     address
2. fname     lname     age     address
3. fname     lname     age     address
4. fname     lname     age     address

Code used :

<?php
$con = mysql_connect("localhost","mysql_user","mysql_password");
if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("test", $con);
?>

<style type='text/css'>
#div1, #div2 {float:left; margin-left:50px; width:300px;}
</style>

<?php
$result = mysql_query("SELECT * FROM member");
$rowcount = mysql_num_rows($result);

echo "<div id='div1'>";
$i = 0;

while($row = mysql_fetch_array($result))
   { 
      echo "Sr. No." . " " . $row['srno'] . " " . $row['fname'] . " " . $row['lname'] . " " . $row['age'] . " " . $row['address'];
   $i++;
   echo "<br/>";
   echo "<br/>";

      if ($i == floor($rowcount / 2)) {

   echo "</div><div id='div2'>";  
    }
   }
echo "</div>";

mysql_close($con);
?>

Output from above code :

Sr. No. 1. fname   lname   age   address               Sr. No. 3. fname   lname   age   address
Sr. No. 2. fname   lname   age   address               Sr. No. 4. fname   lname   age   address

Output required :

Sr. No. 3. fname   lname   age   address               Sr. No. 1. fname   lname   age   address
Sr. No. 4. fname   lname   age   address               Sr. No. 2. fname   lname   age   address

MySQL solution:

You need ORDER BY FIELD( ... in your select statement.

SELECT * FROM member ORDER BY FIELD( id, 3,4,1,2 )

This statement results your records in the following order.

3. fname     lname     age     address
4. fname     lname     age     address
1. fname     lname     age     address
2. fname     lname     age     address

Refer to :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM