What I need:
An efficent SQL Script builder to replace the one below.
The background.
A really simple program but I need a more efficient way of producing it, the reason I am having this code is I need other developers to be able to create ‘modules’ on my platform and database tables, but I am blocking them having full access to the core database, they have to use my $api->database-> access layer to access their tables/data. it blocks any request to the core part of my program.
Below is how I expect to use the functions to build the SQL Create Table Script.
SqlField Class/function just returns a flat array of the values passed, nothing special.
//The structure of the params are..
//$fields[] = SqlField::create($f_name, $f_type, $null, $auto_inc, $is_pk, $is_unique);
$fields[] = SqlField::create('id', 'int(7)', 0, 1, 1, 1);
$sql = $sqlTable->createTable('MyTableName', $fields );
Below is the current function I wrote quickly, but it was getting messy quickly and isnt complete.
public function createTable($tableName, $fields = array()) {
$sql="CREATE TABLE xmod_".$tableName." ( \r\n";
$isinit = true;
foreach($fields as $field) {
$sql .= ($isinit)? "" : ", \r\n" ;
$isinit = false;
$sql .= "".$field[0]." ".$field[1]." ";
if($field[2] == true) {
$sql .= "NOT NULL ";
}
if($field[3] == true) {
$sql .= "auto_increment ";
}
}
$isinit = true;
//Work on the primary keys
foreach($fields as $field) {
if($field[4] == 1) {
$sql .= ($isinit)? "" : ", \r\n" ;
$isinit = false;
$sql .= "PRIMARY KEY (".$field[0].")";
}
}
$isinit = true;
//Work on the unique fields
foreach($fields as $field) {
if($field[5] == 1) {
$sql .= ($isinit)? "" : ", \r\n" ;
$isinit = false;
$sql .= "UNIQUE id (".$field[0].")";
}
}
$sql .= "\r\n )";
return $sql;
}
Though I haven’t tried it myself CodeIgniter provides something similar. http://codeigniter.com/user_guide/database/forge.html
(copied from comment)