将数据库字段显示为多个选择复选框

时间:2012-12-11 08:59:55

标签: php mysql

我有这个代码,我试图使用表格列名称作为复选框值,我的意思是谎言:

$section = mysql_query("SELECT * FROM forma");  
while ($row = mysql_fetch_assoc($section)){
echo "<input type='checkbox' name='data[]' value='" . $firstrow[''] . "' />";

}

我以错误的方式使用它,但是我应该如何以自动方式打印列名作为复选框,而不是手动。

如何使用PDO访问它?

  

$ q = $ dbh-&gt; prepare(“DESCRIBE forma”);   $ Q-&GT;执行(); $ table_fields   = $ q-&gt; fetchAll(PDO :: FETCH_COLUMN);

由于

3 个答案:

答案 0 :(得分:0)

您必须遍历所有列,例如:

$firstrow = false;
while ($row = mysql_fetch_assoc($section)){
    if (!$firstrow) {
        foreach ($row as $column => $value) {
            echo "<input type='checkbox' name='data[]' value='" . $column . "' />"; 
        }
        $firstrow = true;
    }
}

我希望我能正确理解你的问题。

答案 1 :(得分:0)

SHOW COLUMNS与PDO一起使用:

try {
    $dbh = new PDO('mysql:dbname=testdb;host=localhost', 'username', 'passwqord');
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$result = $dbh->query('SHOW COLUMNS FROM forma');

if($result)
{
    foreach($result as $row)
    {
        echo "<input type='checkbox' name='data[]' value='" . htmlspecialchars($row['Field']) . "' />";
    }
}

可以使用DESCRIBE forma代替SHOW COLUMNS检索相同的结果。

答案 2 :(得分:0)

前言:MySQL扩展标记为已弃用,最好使用mysqli或PDO

<小时/> 虽然有mysql_field_nameSHOW COLUMNS这样的功能,但我建议使用INFORMATION_SCHEMA,因为它会为您提供更大的灵活性。

<?php
$database = 'test';
$table = 'forma';

$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error($mysql)); // selecting db is not not necessary in this case

$query = sprintf("
    SELECT
        COLUMN_NAME, COLUMN_TYPE
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = '%s'
        AND TABLE_NAME = '%s'
",
    mysql_real_escape_string($database),
    mysql_real_escape_string($table)
);
$result = mysql_query($query, $mysql) or die(mysql_error($mysql));

while( false!=($row=mysql_fetch_array($result)) ) {
    $name = htmlspecialchars($row['COLUMN_NAME']);
    $type = htmlspecialchars($row['COLUMN_TYPE']);
    printf("<input type=\"checkbox\" name=\"col[]\" value=\"%s\" />%s (%s)<br />\r\n", $name, $name, $type);
}

使用PDO同样的事情

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$stmt = $pdo->prepare('
    SELECT
        COLUMN_NAME, COLUMN_TYPE
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = :database
        AND TABLE_NAME = :table
');
$stmt->execute( array('database'=>'test', 'table'=>'forma') );
foreach( $stmt as $row ) {
    $name = htmlspecialchars($row['COLUMN_NAME']);
    $type = htmlspecialchars($row['COLUMN_TYPE']);
    printf("<input type=\"checkbox\" name=\"col[]\" value=\"%s\" />%s (%s)<br />\r\n", $name, $name, $type);
}