Forum Moderators: coopster

Message Too Old, No Replies

Insert several new fields into mysql table at once

Short-cut to save on typing

         

s9901470

9:26 am on Apr 27, 2005 (gmt 0)

10+ Year Member



Hi

I'd like to create 300 new fields in a mysql table but I don't want to type them out by hand. Could anyone tell me some MySQL syntax to autmate part of this please?

CREATE TABLE questions (q1 VARCHAR(25), q2 VARCHAR(25), q3 VARCHAR(15))

all the way up to q300

Any suggestions?

Thank you in advance.

patrickrock

3:20 pm on Apr 27, 2005 (gmt 0)

10+ Year Member



I would use PHP an array and a loop to spit out the string something like:

<?
$array = range(1,300);

$string = "create table questions (";

foreach ($array as $key=>$val){
$string = $string . "q$val varchar(25),";
}

$string = substr($string, 0, (strlen($string)-1));

$string = $string.")";

echo $string;
?>

updated, I was thinking in a couple of languages at once. This PHP will output the string you want.

you could then do something like


mysql_query($string) or die(mysql_error());

Cheers,
Pat

ncreegan

5:54 pm on Apr 27, 2005 (gmt 0)

10+ Year Member



if this is for your questions/answers db, you don't want 300 columns, you want 300 rows and three columns.

Your table for a simple question/answer table would probably have id (auto incremented), question, answer.

id would be 1,2,3,4 for the question number, your question would store the question associated with that id, and the answer would store the answer associated with that question.

you want your table to look like

id, question, answer
1, where are clouds, the sky
2, where do you wear hats, your head
3, what state is famous for potatoes, idaho

instead of

question 1, question 2, question 3...
where are clouds,,
,where do you wear hats,
,,what state is famous for potatoes

s9901470

7:26 am on Apr 29, 2005 (gmt 0)

10+ Year Member



It was for a different table.

That works great, many thanks. I copied and pasted the string into phpmyadmin SQL area.

Thanks again.