是否有可能以json或xml格式获得mySQL数据库的完整结构?
我正在寻找的是一种获取模式(存储的数据并不重要)的方法,以使用它为应用程序创建后端/crud。
发布于 2017-07-07 00:30:15
对于这个问题,这不是一个全面的答案,因为它没有返回一个json。但是它是一个简单的类,它提供了有关表作为对象的所有相关信息。这可以很容易地转换为返回一个json。
类依赖于传递实现rawQuery方法的db对象,就像PHP-Mysqli-数据库-类一样。但是,如果需要的话,可以轻松地重写extractTableInfo方法。
<?php
Class dbHelper {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function extractTableInfo($tableName) {
$result = $this->db->rawQuery("DESCRIBE `".$tableName."`");
$tableInfo = array();
foreach ($result as $key => $value) {
$info = new \stdClass();
$info->name = $value['Field'];
$info->type = $this->_getColumnType($value['Type']);
$info->length = $this->_getLength($value['Type']);
$info->hasNull = $this->_getNull($value['Null']);
$info->default = $this->_getDefault($value['Default']);
$tableInfo[] = $info;
}
return $tableInfo;
}
public function getIndexes($tableName) {
$result = $this->db->rawQuery("SHOW INDEX FROM `".$tableName."`");
return $result;
}
private function _getLength($info) {
$pattern = '/\({1}([\d\W]*)\){1}/';
preg_match($pattern, $info, $matches);
return isset($matches[1]) ? $matches[1] : NULL;
}
private function _getColumnType($info) {
$pattern = '/([\w]*)(\([\d\W]*\))*/';
preg_match($pattern, $info, $matches);
return isset($matches[1]) ? $matches[1] : NULL;
}
private function _getNull($info) {
if($info==='NO') {
return false;
} else {
return true;
}
}
private function _getDefault($info) {
if($info>='') {
return $info;
} else {
return NULL;
}
}
}用法:
$db = YOUR DATABASE OBJECT/CLASS;
$dbHelper = new dbHelper($db);
$tableName = "test";
$tableInfo = $dbHelper->extractTableInfo($tableName);
echo json_encode($tableInfo);要获得数据库中所有表的列表,您需要:
SHOW TABLES [in dbname]或者跟随这个问题
然而,有许多具有不同效益/产出的替代办法:
mysqldump -u root -p --no-data dbname > schema.sqlhttps://stackoverflow.com/questions/44960665
复制相似问题