有没有办法在表格中获取SET字段的可用值?
谢谢。
答案 0 :(得分:3)
您可以使用DESCRIBE myTableName mySetColumn
或SHOW COLUMNS FROM myTableName LIKE mySetColumn
检索SET字段的可能值:
mysql> DESCRIBE myTableName mySetColumn;
+-------+-------------------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------------------------------------+------+-----+---------+-------+
| myset | set('Travel','Sports','Dancing','Dining') | YES | | NULL | |
+-------+-------------------------------------------+------+-----+---------+-------+
答案 1 :(得分:2)
SELECT `COLUMN_TYPE` FROM `information_schema`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'my_database_name'
AND `TABLE_NAME` = 'my_table_name'
AND `COLUMN_NAME` = 'my_set_column';
仅为您提供类型,例如
set('Travel','Sports','Dancing','Dining')
你仍然需要在文本基础上提取设定值,但这样的方法就不那么杂乱了。
答案 2 :(得分:2)
从@Andy链接到文档的完整实现:
/**
* @return array
* @param table DB table
* @param column Column name
* @desc Return an array of the possible values for a SET
*/
function get_set($table,$column)
{
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
if (!($ret = mysql_query($sql)))
die("Error: Could not show columns");
$line = mysql_fetch_assoc($ret);
$set = $line['Type'];
// Remove "set(" at start and ");" at end.
$set = substr($set,5,strlen($set)-7);
// Split into an array.
return preg_split("/','/",$set);
}
答案 3 :(得分:0)
以下是如何使用PDO扩展获取SET的可能值。
function get_set($table, $column)
{
global $db; //PDO DB Handler
$sql = "SHOW COLUMNS FROM $table LIKE :column";
$stmt = $db -> prepare($sql);
$stmt -> bindParam(":column", $column, PDO::PARAM_STR, 50);
try {
$result = $stmt -> execute();
$row = $stmt -> fetch(PDO::FETCH_ASSOC);
$set = $row['Type'];
$set = substr($set,5,strlen($set)-7);
// Split into an array.
return preg_split("/','/",$set);
} catch (PDOException $e) {
echo $e -> getMessage();
return false;
}
}
答案 4 :(得分:0)
上述方法对我来说并不完全正常,但我最终得到了这个并且效果很好。发布以防万一在相同情况下帮助其他人。您只需根据结果修剪字符串,因为它会将您的列名称与“set”一词包括在一起。
<?php>
include ('database.php');
$query = "SHOW COLUMNS FROM Products LIKE 'Genre'";
$stmt = $con->prepare( $query );
$result = $stmt -> execute();
if ($result) {
$row = $stmt -> fetch(PDO::FETCH_ASSOC);
$genres = implode($row);
$genres = substr($genres,10,strlen($genres)-14);
//echo $genres;
$genres = preg_split("/','/",$genres);
//this is to populate my select box options with set values
echo "<select name = 'genre'>";
echo "<option>Select...</option>";
foreach ($genres as $key=>$value) {
echo "<option name = '$value' value = '$value'>$value</option>";
};
echo "</select>";
}
?>