0

I am currently trying to build a database manager with appealing GUI for specific functions. One of the functions is to create a TABLE from a list of variable, where each element is one of the variable. Like this:

<?php 

include('conn.php');

var[0]='clients';
var[1]='id int(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY';
var[2]='name VARCHAR(30) NOT NULL';
var[3]='surname VARCHAR(30) NOT NULL';

$create = "CREATE TABLE var[0] (
rest of vars
)";

...
?>

Really stuck here, guys.

2
  • 2
    This sounds like a bad idea Commented Dec 19, 2015 at 16:30
  • @Strawberry, it probably is a bad idea, but I don't see any other way of giving user a flexibility of adding new tables. Commented Dec 19, 2015 at 16:40

2 Answers 2

2

You can try this way:

<?php

include('conn.php');

$var[0]='clients';
$var[1]='id int(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY';
$var[2]='name VARCHAR(30) NOT NULL';
$var[3]='surname VARCHAR(30) NOT NULL';

$create = "CREATE TABLE $var[0] (
  $var[1],$var[2], $var[3]
)";


...
?>

Moreover, to add those $vars dynamically instead of manually you can do something like this:

$create = "CREATE TABLE $var[0] (";
for($i = 1; $i < count($var) - 1; $i++){
  $create.= $var[$i].",";
}
$create .= $var[$i].")";

Now you can execute the $create string as query;

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

2 Comments

This would probably work, but I would like to no have to list all variables manually.
small typo as $var[i] should be $var[$i].
1

Another method would be like this:

$tableName = array_shift($var);
$columns = implode(', ', $var);

$create = "CREATE TABLE {$tableName} ({$columns}))";

And also it would be a much cleaner approach.

Comments

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.