I am trying to execute some queries in php, but I don't know how many columns there are, or what their names are. Basically, I want to recreate a SQL table in php, dynamically/generically. Any ideas? Thanks
$sql="Select * from a"; $intField=0; //Used to get the field type later $sqlIns="create table a("; $r=mysql_query($sql); while($ary=mysql_fetch_array($r, MYSQL_ASSOC)){ foreach( $ary as $col => $val){ //This foreach will scan each column sequentially //by their names. Do whatever you want here. $type=mysql_field_type($r,$intField); $len=mysql_field_len($r,$intField); $sqlIns.="$col$type($len),\r\t"; $intField++; } } $sqlIns.=");"; //And here you have your create table query... echo $sqlIns;
__________________
Only a biker knows why a dog sticks his head out the window.
Hmm, yeah. I believe I have misplaced the counter declaration.
Try to move it into the while loop, like this:
PHP Code:
$sql="Select * from a"; $sqlIns="create table a("; $r=mysql_query($sql); while($ary=mysql_fetch_array($r, MYSQL_ASSOC)){ $intField=0; //Used to get the field type later foreach( $ary as $col => $val){ //This foreach will scan each column sequentially //by their names. Do whatever you want here. $type=mysql_field_type($r,$intField); $len=mysql_field_len($r,$intField); $sqlIns.="$col$type($len),\r\t"; $intField++; } } $sqlIns.=");"; //And here you have your create table query... echo $sqlIns;
</span></span>
__________________
Only a biker knows why a dog sticks his head out the window.
« Reply to Unknown amount of columns in select statement