Skip to content

Instantly share code, notes, and snippets.

@easai
Created February 25, 2014 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save easai/9217563 to your computer and use it in GitHub Desktop.
Save easai/9217563 to your computer and use it in GitHub Desktop.
function tableStructure($tableName)
{
try
{
// Retrieve field names and types
$sql="DESCRIBE $tableName";
$resultSet=$this->query($sql);
$list=array();
while($row=mysql_fetch_array($resultSet,MYSQL_ASSOC))
{
if($row['Default']=='CURRENT_TIMESTAMP')
{
array_unshift($list,$row);
}
else
{
array_push($list,$row);
}
}
$html="";
foreach($list as $row)
{
$field=$row['Field'];
$type=strtoupper($row['Type']);
if($row['Null']==0)
{
$null=" NOT NULL";
}
$default="";
if($row['Default']!=NULL)
{
if($row['Default']=='CURRENT_TIMESTAMP')
{
$default=" DEFAULT ".$row['Default'];
}
else
{
$default=" DEFAULT '".$row['Default']."'";
}
}
$extra="";
if($row['Extra']!="")
{
$extra=" ".$row['Extra'];
}
if($row['Key']=="PRI")
{
if(!empty($html))
{
$html.=",\n";
}
$html.="PRIMARY KEY (`$field`)";
}
if(!empty($html))
{
$html.=",\n";
}
$html.="`$field` $type$null$default$extra";
}
$html=<<<END
DROP TABLE IF EXISTS `$tableName`;
CREATE TABLE `$tableName` (
$html
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
END;
}
catch(Exception $e)
{
echo trace(debug_backtrace());
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment