-2

我有这个代码,我试图使用它来将表列名称显示为复选框值,我的意思是这样的:

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

}

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

如何使用 PDO 到达它?

$q = $dbh->prepare("DESCRIBE 格式"); $q->执行(); $table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

谢谢

4

3 回答 3

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;
    }
}

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

于 2012-12-11T09:05:19.643 回答
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

于 2012-12-11T09:10:53.930 回答
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);
}
于 2012-12-11T09:14:46.387 回答