Tuesday 15 July 2014

php - mysql create dynamic tables -



php - mysql create dynamic tables -

i trying create table dynamically , problem facing creating columns dynamically. mean won't have fixed number of columns tried representing variable when run code gives me error. below tried.

the error

you have error in sql syntax; check manual corresponds your... $colarray = array(); foreach($ml $df){ $colarray[] = "`".$df."` varchar(250) not null,<br/>"; } $columns = implode("",$colarray); $sql = "create table if not exists {$table_name}( id int not null auto_increment, username varchar(250) not null, {$columns} date varchar(250) not null, primary key (id) )"; $stmt = $db->prepare($sql); echo $db->error; $stmt->execute();

this should work:

$colarray = array(); // since want these 2 columns in order // assign here $colarray[] = "id int not null auto_increment"; $colarray[] = "username varchar(250) not null"; foreach($ml $df) { $colarray[] = "`".$df."` varchar(250) not null"; } // since want column last, assign here $colarray[] = "date varchar(250) not null"; $columns = implode(",\r\n",$colarray); $sql = "create table if not exists {$table_name}( {$columns}, primary key (id))"; $stmt = $db->prepare($sql); echo $db->error; $stmt->execute();

php mysql

No comments:

Post a Comment