1

I'm trying to create a SQL table in PHP using the following code:

$sql = "CREATE TABLE `$DBName`.`$login`_clients  (
  ClientID int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ClientID`),
  AgentClients varchar(15),
  ClientTotal int
)";     

The botton script runs fine and saves the database as my $login query. I wanted to save the table as $login_clients however. Ex. $login="Fred", then the table would be named Fred_clients. I have tried a few different methods of combining variables with text but can't get the format down. Any suggestions?

$sql = "CREATE TABLE `$DBName`.`$login`_clients  (
  ClientID int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ClientID`),
  AgentClients varchar(15),
  ClientTotal int
)";    
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Blaine Hurtado
  • 139
  • 2
  • 17

2 Answers2

4

You just have your back tick in the wrong place, it should go after _clients. The problem you likely ran into was that the PHP interpreter then thought your variable was called $login_clients instead of $login, which can be solved by wrapping the variable in curly braces {}.

$sql = "CREATE TABLE `{$DBName}`.`{$login}_clients`  (
  ClientID int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ClientID`),
  AgentClients varchar(15),
  ClientTotal int
)";   
doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • 2
    You'll want to be super mega careful that `$login` does not contain anything harmful here. – tadman Oct 29 '12 at 20:28
  • 1
    Also note the proper use of encapsulation in the answer. Encapsulation is very important. – Yitzhak Oct 29 '12 at 20:28
  • @doublesharp thanks for your help, this clears up my questions on braces! Once I can choose an answer, this will be it. :) – Blaine Hurtado Oct 29 '12 at 20:30
  • @BlaineHurtado no problem - take note of what @tadman posted as well, you want to make sure that your `$login` variable is what you expect it to be, if you are accepting input from a form for example this could be used for a SQL injection attack. – doublesharp Oct 29 '12 at 20:33
  • @doublesharp This page requires a valid session cookie through a previous login. Other than sanitizing values and checking for input validations/existing logins, would you recommend other extra securities? Once again, everyone's help is greatly appreciated! – Blaine Hurtado Oct 29 '12 at 20:39
0

This should work

$sql = "CREATE TABLE `$DBName`.`" . $login . "_clients`  (
  ClientID int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ClientID`),
  AgentClients varchar(15),
  ClientTotal int
)";
Adi
  • 49
  • 2