php从mysql中检索多个数据

时间:2012-04-08 18:05:26

标签: php mysql forms select insert

我使用php post form从我的复选框中将多个id插入MySQL数据库。在示例中,我将id(复选框值表test)插入到mysql中。现在我需要一个函数来从MySQL检索数据并使用我的示例输出打印到我的页面(打印表test的水平列表名称,其中data = userid)

我的复选框值(表名为test):

 id | name
----+-------
  1 | test1
  2 | test2
  3 | test3
  4 | test4
  5 | test5
  6 | test6
  7 | test7
  9 | test9

MySQL数据插入(表usertest的名称):

 id | data    | userid
----+---------+--------
  1 | 1:4:6:9 | 2
  2 | 1:2:3:4 | 5
  3 | 1:2     | 7

示例输出:(打印表测试的水平列表名称,其中data = userid)

user id 2 choise : test1 - test4 - test6 - test9

由于

1 个答案:

答案 0 :(得分:2)

假设您的usertest表只有示例中列出的三列,您应该将其替换为以下内容 -

CREATE TABLE usertest (
    data INTEGER NOT NULL,
    userid INTEGER NOT NULL,
    PRIMARY KEY (data, userid)
);

然后你的数据看起来像 -

+------+--------+
| data | userid |
+------+--------+
|  1   |   2    |
|  4   |   2    |
|  6   |   2    |
|  9   |   2    |
|  1   |   5    |
|  2   |   5    |
|  3   |   5    |
|  4   |   5    |
|  1   |   7    |
|  2   |   7    |
+------+--------+

查询这些数据然后变得微不足道了 -

SELECT usertest.userid, GROUP_CONCAT(test.name SEPARATOR ' - ')
FROM usertest
INNER JOIN test
    ON usertest.data = test.id
GROUP BY usertest.userid

您可以阅读有关GROUP_CONCAT here

的更多信息

您可以使用PHP解决方案并将可能的复选框值存储在由其ID标记的数组中。像 -

这样的东西
<?php

$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'pass');
$sql = 'SELECT id, name FROM test';

$stmt = $db->prepare($sql);
$stmt->execute();

$array = array();

while ($row = $stmt->fetchObject()) {
    $array[$row->id] = $row->name;
}

$sql = 'SELECT userid, data FROM usertest';

$stmt = $db->prepare($sql);
$stmt->execute();

while ($row = $stmt->fetchObject()) {
    $data = explode(':', $row->data);
    foreach($data as $key => $val) {
        $data[$key] = $array[$val];
    }
    print "user id {$row->userid} choise : " . implode(' - ', $data) . "<br/>\n";
}