我的数据库表字段看起来像这样

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

关于php - 将SQL表字段输入转换为HTML表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37137439/

10-16 15:37