Jump to content

[SOLVED] using array to update a table


jeff5656

Recommended Posts

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

<?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());
?>

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

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());
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.