前言:MySQL 扩展被标记为已弃用,最好使用 mysqli 或PDO
虽然有
mysql_field_name或
SHOW 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);
}