Click here to Skip to main content
15,886,072 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Scenario:

TO crate a table we use the query as shown below

PHP
$query = 'CREATE TABLE xyz ' .
			'(Id varchar(30), Val varchar(30))';


Here the table name is "xyz". I know the table name so i was able to create it. In the next case i do not know the name of the table and the name is in the variable $TableName. How do i create the table now

PHP
$TableName = "xyz"; -->Calculated in run time
$query = 'CREATE TABLE '.$TableName.' ' .
			'(Id varchar(30), Val varchar(30))';


When i execute the table is not being created. Is this format correct?
Posted
Comments
enhzflep 3-Apr-13 13:05pm    
See here: Can Php Pdo statements accept the table name as parameter?

Yes, the format is correct.
Summary: Can't bind either a column name or a table name. You have to use string concatenation.
Prasad Khandekar 3-Apr-13 17:02pm    
I am sure he is using string concatenation. ($query = 'CREATE TABLE ' . $TableName . ' ' . '(Id varchar(30), Val varchar(30))';
enhzflep 3-Apr-13 17:44pm    
Me too. It's an odd question - examples of string concatenation yet nothing that is specific to pdo (at least, so it seems).
Even the strings that are concatenated could simply be written in a single expression.
For instance, I still cannot work out why one would write this

$query = 'CREATE TABLE xyz ' .
'(Id varchar(30), Val varchar(30))';

instead of

$tblName = 'someName';
$query = "CREATE TABLE $tblName (Id varchar(30), Val varchar(30))";

or

$tblName = 'someName';
$query = 'CREATE TABLE ' . $tblName . ' (Id varchar(30), Val varchar(30))';

or even

$tblName = 'someName';
$query = sprintf('CREATE TABLE %s (Id varchar(30), Val varchar(30))', $tblName);


I'd naturally have expected to see something like the following code. That is until I realized that prepared statements are but one of the advantages of Pdo - the other being the fact it works with a bunch of different DBs, i.e sqLite.

$params = array(':tableName' => 'xyz');
$query = $pdo->prepare('select * from :tableName');
$query->execute();
Prasad Khandekar 3-Apr-13 17:11pm    
Hello Amarsat,

The problem might be in the table name generation. Have you tried running the second snippet in which the $TableName is set to value "xyz". Please also have a look at (http://www.w3cyberlearnings.com/PHP_MySQL_PDO_Create_Table)
Member 12880505 1-Dec-16 2:55am    
Sir,can you please tell me how to take variable as column name in create query.That to in foreach loop

1 solution

PHP
$query = "CREATE TABLE $TableName".
                 '(Id varchar(30), Val varchar(30))';


This has worked fine. Thanks for all your support enhzflep and Prasad
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900