[編輯註記:在 MySQL v5.0+ 中,您可以使用 INFORMATION_SCHEMA 表格來檢索關於表格、視圖、資料庫等等的資訊。 --zak@php.net]
這是一個小的函式,用來解析 MySQL 建立表格的 DDL。這個函式接受一個包含建立表格的 SQL 程式碼的字串,並返回表格名稱、表格欄位、表格索引鍵欄位和欄位類型,所有這些都以陣列形式返回(顯然除了名稱之外)。這個函式要求主鍵被命名為 "id",而外鍵被命名為 "id..."。所有外鍵類型都被假設為 int(或其變體,如 bigint 等)。所有這些限制都可以很容易地修改以適應其他需求。
這是一個 DDL 程式碼的範例。
CREATE TABLE `telefones` (
`id` int(11) NOT NULL auto_increment,
`id_tipo_telefone` int(11) NOT NULL default '0',
`numero` varchar(15) NOT NULL default '',
`id_pessoa` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `id_tipo_telefone` (`id_tipo_telefone`),
KEY `id_pessoa` (`id_pessoa`),
CONSTRAINT `0_775` FOREIGN KEY (`id_tipo_telefone`) REFERENCES `tipos_telefone` (`id`),
CONSTRAINT `0_776` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoas` (`id`)
) TYPE=InnoDB
這會返回
$tbname = "telefones"
$fields = array("numero");
$kfields = array("id_tipo_telefone","id_pessoa");
$tipos = array("varchar");
希望對您有所幫助...
<?php
function parseQuery($Q, &$tbname, &$fields, &$kfields, &$tipos) {
$Q = str_replace(array(chr(10),chr(13))," ",$Q);
$Q = str_replace(array("'","`")," ",$Q);
preg_match("/([^(]*)\((.*)\)(.*)/",$Q,$A);
$part1 = $A[1];
$part2 = $A[2];
$part3 = $A[3];
preg_match("/(.*) ([a-zA-Z_]+)/",$part1,$A);
$tbname = strtolower($A[2]);
$temp = split(",",$part2);
foreach ($temp as $t) {
preg_match("/ *([a-zA-Z_]+) +([a-zA-Z_]+)(.*)/",$t,$A);
$pcampo = strtolower($A[1]);
$ptipo = strtolower($A[2]);
if (!preg_match("/$pcampo/","primary key constraint id unique foreign") ) {
if ( ($pcampo[0] == "i") && ($pcampo[1] == "d") )
$kfields[] = $pcampo;
else {
$fields[] = $pcampo;
$tipos[] = $ptipo;
}
}
}
}
?>