簡體   English   中英

將SQL表字段輸入轉換為HTML表

[英]Convert Sql table field input into HTML table

我的數據庫表字段看起來像這樣

id - name  - school      - subjects                    -  marks

1  - Adam  - Highschool  - Geography,physics,math      -  60,50,40

2- - Jhone - elementry   -  Math,Language,Geography     - 90,20,10

php文件應使用引導程序將此值轉換為html表

我期望的結果是這樣的

Hello Jone! this is your results
Math : 90
Language : 20
Geography : 10 

我嘗試了不同的方法,例如將結果轉換為數組,但確實可以滿足我的要求。

其中之一是

<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
               array("title"=>"daisy", "price"=>0.75 , "number"=>25),
               array("title"=>"orchid", "price"=>1.15 , "number"=>7) 
             ); 
?>

<?php if (count($shop) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

任何建議

謝謝

規范化數據並避免數據庫中用逗號分隔的列表將非常有用。 但是,您可以使用explode()輕松實現此目的:

輸入:

mysql> select * from marks;
+----+------+-------------+-------------------------+----------+
| id | name | school      | subjects                | marks    |
+----+------+-------------+-------------------------+----------+
|  1 | Adam | High School | Geography,physics,math  | 60,50,40 |
|  2 | Jone | Elementary  | Math,Language,Geography | 90,20,10 |
+----+------+-------------+-------------------------+----------+
2 rows in set

PHP代碼:

<?php
    $con = mysqli_connect('localhost','root','','test') or die(mysqli_error($con));
    $query = "SELECT * FROM marks";
    $result = mysqli_query($con,$query) or die(mysqli_error($con));
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            $subject = explode(',',$row['subjects']);
            $marks = explode(',',$row['marks']);
            echo 'Hello '.$row['name'].'! This is your results:';
            echo '<table>';
                foreach($subject as $k=>$s){
                    echo '<tr>
                        <td>'.$s.'</td>
                        <td>'.$marks[$k].'</td>
                    </tr>';
                }
            echo '</table>';
        }
    }
?>

輸出是每個用戶的表:

Hello Adam! This is your results:
Geography   60
physics     50
math        40

Hello Jone! This is your results:
Math        90
Language    20
Geography   10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM