jeff5656 Posted November 30, 2008 Share Posted November 30, 2008 I want to add 31 new fields to the table called "staffsched". Is there a way to do this with an array (or some kinf of WHILE loops) so I don't have to type them all? The onhly difference in these name is the number at the end (1 thru 31): <?php include ("connectdb.php"); $sql = "ALTER TABLE staffsched ( wn1 varchar(20) NOT NULL, wn2 varchar(20) NOT NULL, etc )"; // Execute query mysql_query($sql) or die(mysql_error()); ?> Link to comment https://forums.phpfreaks.com/topic/134879-solved-using-array-to-update-a-table/ Share on other sites More sharing options...
rhodesa Posted November 30, 2008 Share Posted November 30, 2008 <?php include ("connectdb.php"); //Build query $alters = array(); for($n=1;$n <= 31;$n++) $alters[] = sprintf('wn%s varchar(20) NOT NULL',$n); $sql = "ALTER TABLE staffsched ( ".implode(',',$alters).")"; // Execute query mysql_query($sql) or die(mysql_error()); ?> Link to comment https://forums.phpfreaks.com/topic/134879-solved-using-array-to-update-a-table/#findComment-702293 Share on other sites More sharing options...
jeff5656 Posted November 30, 2008 Author Share Posted November 30, 2008 With that code I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( wn1 varchar(20) NOT NULL,wn2 varchar(20) NOT NULL,wn3 varchar(20) NOT NULL,wn4' at line 1 Link to comment https://forums.phpfreaks.com/topic/134879-solved-using-array-to-update-a-table/#findComment-702294 Share on other sites More sharing options...
rhodesa Posted November 30, 2008 Share Posted November 30, 2008 i assumed your syntax for alter table was correct...try this: <?php include ("connectdb.php"); //Build query $alters = array(); for($n=1;$n <= 31;$n++) $alters[] = sprintf('wn%s varchar(20) NOT NULL',$n); $sql = "ALTER TABLE staffsched ADD COLUMN ( ".implode(',',$alters).")"; // Execute query mysql_query($sql) or die(mysql_error()); ?> Link to comment https://forums.phpfreaks.com/topic/134879-solved-using-array-to-update-a-table/#findComment-702303 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.