php - 将Sql表字段输入转换为HTML表

标签 php mysql

我的数据库表字段如下所示

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/

相关文章:

php - 经常提取大量行——我这里需要 memcached 吗?

mysql - 在 MySQL 查询中对记录子集执行一些算术运算

javascript - 是否可以从浏览器控制台更改 JS 变量值?

javascript - 通过 jQuery AJAX 将多个数组从 PHP 传递到 Javascript

javascript - 多个 JSON 数组作为响应 - AJAX 和 PHP

php - 聊天室在线用户列表实现

php - 使用 ORDER BY 或 PHP 排序函数对 MySQL 查询进行排序

MYSQL 查询通过在逗号分隔的字符串中查找其 id 来计算项目的后代

mysql - Symfony2-Doctrine2-MySql : Composite FK and PK

php - 如何同时向两个表插入数据?