Page 1 of 1

Problem writing a for loop for SQL

Posted: Thu Apr 09, 2009 12:02 pm
by Anarking
Hi there, im having problems trying to write this loop out

mysql_query("CREATE TABLE ".$Contents."(
PID INT (10) UNSIGNED not null AUTO_INCREMENT PRIMARY KEY,"
for ($x = 0; $x < ((count($rows)-2)/6); $x++)
{
$rows[3+($x*6)]

" VARCHAR(100),
}
)")
or die(mysql_error());

Basically, I got an array that has names for each column in the table and I want to iterate through it to end up with something like this.

mysql_query("CREATE TABLE constructor(
PID INT (10) UNSIGNED not null AUTO_INCREMENT PRIMARY KEY,
Row1 VARCHAR(100),
Row2 VARCHAR(100),
Row3 VARCHAR(100)
)")
or die(mysql_error());


Any ideas what im doing wrong?

Re: Problem writing a for loop for SQL

Posted: Thu Apr 09, 2009 1:04 pm
by nyoka
Personally I would create the sql before executing the query, that way you can remove the final comma from the field list.

Assuming the array of fields you have is similar to:

Code: Select all

 
<?php
$rows = array("Row1", "Row2", "Row3");
?>
 
The following will work:

Code: Select all

 
<?php
$sql = "CREATE TABLE ".$Contents."(PID INT (10) UNSIGNED not null AUTO_INCREMENT PRIMARY KEY,";
foreach ($rows AS $i)
    $sql .= "$i VARCHAR(100),";
$sql = substr($sql, -1) . ")";
mysql_query($sql) or die(mysql_error());
?>
 
If this is not suitable can you post an example of your array containing the fields.