Skip to content

Instantly share code, notes, and snippets.

@SeanJA
Created March 10, 2011 16:53
Show Gist options
  • Save SeanJA/864446 to your computer and use it in GitHub Desktop.
Save SeanJA/864446 to your computer and use it in GitHub Desktop.
<?php
/**
* Get the schema definition of a table, or the whole database schema.
*
*
* @param $table The name of the table. If not given, the schema of all tables is returned.
* @param $rebuild If true, the schema will be rebuilt instead of retrieved from the cache.
*/
function get_schema($table = NULL, $rebuild = FALSE) {
static $schema = array();
if (empty($schema) || $rebuild) {
// Try to load the schema from the cache table.
if (!$rebuild && $cached = cache_get('schema')) {
$schema = $cached['data'];
}
// Otherwise, rebuild the schema cache.
else {
$schema = array();
$query1 = "SHOW TABLES FROM '$db_name'";
while($result = fetch_assoc($query1)){
$query = "SHOW COLUMNS FROM '$result['table']'";
$tmp = fetch_assoc($query);
$schema[$table] = $tmp[0];;
}
//save the schema back to the cache table
//upsert into cache where cid = 'schema' set data = $schema, created = now();
cache_set('schema', $schema);
}
}
if (!isset($table)) {
return $schema;
}
elseif (isset($schema[$table])) {
return $schema[$table];
}
else {
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment