简体   繁体   中英

How to display data in a specific numbered position using php and mysql?

I have a scenario like this: I will take a number as input and will store in the database along with other information. And will display the data from the database as per the number position that have been taken as input. For example: if the input is 4, the display order will be in fourth position. I want to make this using PHP/Mysql. Thanks for the suggestions...

suppose you have field serial_number in your table iserted for serial by input, then firstlly you have to fetch table in array and then sort the table according to the serial number the code is like follow

<?php 
$con=mysql_connect("localhost","root","");
$sql="select * from sort.data";
$result=mysql_query($sql,$con);
$data=array();
while($row=mysql_fetch_assoc($result))
{
  $data[]=$row; 
}
echo '<br />content of data before sorting';
echo '<pre>';
print_r($data);
echo '</pre>';

$final = array();
foreach($data as $key=>$item)
{
    for($i=0;$i<$key;$i++)
    {
        if($data[$i]['serial_number']>$data[$key]['serial_number'])
        {
            $temp = $data[$key];
            $data[$key] = $data[$i];
            $data[$i]   = $temp;
        }   
    }   
}
echo '<br />content of data after sorting';
echo '<pre>';
print_r($data);
echo '</pre>';
?>

here lastly $data containing the sorted array as per your requirement then you applay the table and td on it for formatting

as Saurabh Sinha commented. I am describing his comment. store your input value in table such as position

$position = $_REQUEST['position']; // position submit by your form eg:4

insert record with position

mysql_query("INSERT INTO `your_table`(field1, field2,....,position) VALUES('$field1_value', '$field2_value',.....,'$position')");

now when ever you retrive your records and be sort according to the position. using ORDER BY like this

$sql = "SELECT * FROM `your_table` WHERE [YOUR CONDITIONS] ORDER BY position [DESC/ASC]";

in [] optional. eg : if you have no condition to apply and want to order in Descending use given query

$sql = "SELECT * FROM `your_table` ORDER BY position DESC";

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