0

This is the code:

<?php
$months= array("january", "november", "december");
$db_server = include('root.php');
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db('info');
for ($i=0; $i < $months; $i++){
    $query1 = "CREATE TABLE {$months[$i]} (
    StIDf CHAR(10) NOT NULL, FulNam TEXT NOT NULL, ComNam TEXT NOT NULL,Add TEXT ,Tel TEXT )";
}
?>

But it's not working. I need to create several tables from one loop. Is it possible to do that?

2
  • 3
    Please don't do that. Just have one table and add an extra column for the month. Commented Sep 16, 2012 at 17:33
  • my table is really big to type and it makes the coding so big so i thought to make a table via loop Commented Sep 25, 2012 at 16:56

2 Answers 2

1

Try this:

<?php
$months    = array("january","november","december");
$db_server = include('root.php');

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db('info');

foreach($months as $month) {
    $query1 = "CREATE TABLE {$month}  ( "
            . "StIDf CHAR(10) NOT NULL, "
            . "FulNam TEXT NOT NULL, "
            . "ComNam TEXT NOT NULL, "
            . "Add TEXT, "
            . "Tel TEXT "
            . ")";
    $result = mysql_query($query1);
}
?>

Your code was not executing the mysql_query (or the alternatives from mysqli or PDO) so nothing was executed in the database.

Sign up to request clarification or add additional context in comments.

Comments

1

You are never performing the actual query, add this line to inside the for-loop:

mysql_query($query1);

Also, you should use count($month) to find out how many items it contains.

for ($i = 0; $i < count($months); $i++) {
    $query1 = "CREATE TABLE {$months[$i]}  (
    StIDf CHAR(10) NOT NULL,FulNam TEXT NOT NULL, ComNam TEXT NOT NULL,Add TEXT ,Tel TEXT )";
    mysql_query($query1);
}

Also, I suggest using mysqli or mysql PDO instead of the old, will be deprecated in the future, mysql API. Read more about that here: https://www.php.net/manual/en/mysqlinfo.api.choosing.php

1 Comment

i was just started php i'll try mysqli

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.