如何使用MySQL中的预准备语句动态地转动表

时间:2015-02-23 16:46:40

标签: php mysql

我需要使用MySQL中的prepared语句动态调整html表。 sql代码很好(经过测试)。我想要的是如何在PHP中集成此查询,以便我可以在我的网页中显示它。这是我想要展示的内容

<table>
    <tr>
        <th>VOL_ID</th>
        <th>VOL_GIV_NAME</th>
        <th>VOL_FAM_NAME</th>
        <th>2015-02-03</th>
        <th>2015-02-04</th>
        <th>2015-02-05</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Jack</td>
        <td>Napper</td>
        <td>(null)</td>
        <td>A</td>
        <td>P</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Sylvie</td>
        <td>Tingle</td>
        <td>P</td>
        <td>(null)</td>
        <td>A</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Floy</td>
        <td>Stambaugh</td>
        <td>(null)</td>
        <td>(null)</td>
        <td>P</td>
    </tr>
</table>

SQL:

SQL:
create table volunteer
(
  vol_id int,
  vol_giv_name varchar(15),
  vol_fam_name varchar(15),
  PRIMARY KEY (`vol_id`)

);
insert into volunteer values
(1, 'Jack', 'Napper'),
(2, 'Sylvie', 'Tingle'),
(3, 'Floy', 'Stambaugh');


create table volunteer_attendance
(
  att_id int,
  vol_id int,
  att_date varchar(15),
  vol_att char(1),
  PRIMARY KEY (`att_id`)
);
insert into volunteer_attendance values
(1,  '2', '"2015-02-03"', 'P'),
(2,  '1', '"2015-02-04"', 'A'),
(3,  '1', '"2015-02-05"', 'P'),
(4,  '2', '"2015-02-05"', 'A'),
(5,  '3', '"2015-02-05"', 'P');

查询:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(va.att_date = ''',
      att_date,
      ''', va.vol_att, NULL)) AS ',
      att_date
    )
  ) INTO @sql
FROM volunteer_attendance;

SET @sql = CONCAT('SELECT v.vol_id
                    , v.vol_giv_name
                    , v.vol_fam_name, ', @sql, ' 
                   FROM volunteer v
                   LEFT JOIN volunteer_attendance AS va 
                    ON v.vol_id = va.vol_id
                   GROUP BY v.vol_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

0 个答案:

没有答案