1

What's wrong with the following code:

$table = $email . "Entries";
$query = "CREATE TABLE ".$table."(FirstName varchar(15),LastName varchar(15),Age int)";

I want to create a table whose name is dynamic based on a posted variable. The above doesn't work however. I have also tried:

$query = "CREATE TABLE $table(FirstName varchar(15),LastName varchar(15),Age int)";

Any Ideas?

4
  • 1
    What error are you getting? Use mysql_error() to see what error MySQL is returning. Commented Jul 27, 2011 at 19:37
  • make sure to catch if ur trying to create tables with the same name Commented Jul 27, 2011 at 19:38
  • The method you are using look as though it is wide open to SQL injection. Are you escaping $email before using it? Is it really necessary to create a table from a posted value, or could another more secure method be used? Commented Jul 27, 2011 at 19:41
  • 1
    Any reason you're creating a table to store what would seem to be just one record? Why not a single table with email,FirstName,LastName,Age fields? Commented Jul 27, 2011 at 19:48

2 Answers 2

3

I cannot find the relevant documentation, but would assume that if $email contains an @ this would be an invalid table name in MySQL.

CREATE TABLE [email protected] (FirstName varchar(15),LastName varchar(15),Age int)

If this is the case, try enclosing the table name in backticks:

$query = "CREATE TABLE `$table` (FirstName varchar(15),LastName varchar(15),Age int)";
Sign up to request clarification or add additional context in comments.

3 Comments

Or a space or any number of other invalid characters. @user559142 - what sort of validation are you performing on the input?
MySQL Docs you were referring to. @ is only valid in backticks.
@cularis Thank you. I was searching for "identifiers" rather than "object names"
0

$query = "CREATE TABLE $table(FirstName varchar(15),LastName varchar(15),Age int)"; I am not too sure if you can have "@" in the name of a table....

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.