Forum Moderators: coopster

Message Too Old, No Replies

Creating a Table with $ Variable

         

HoboTraveler

6:10 pm on Jan 15, 2007 (gmt 0)

10+ Year Member



Hello,

I need to create a table with a $ variable in the table name. The code below does not work. Could someone point me in the right direction..

TIA

-- begin code --
<?php

$table = 'test';

$SqlInsertQuery = "CREATE TABLE {$table} ('
. ' `ID` int(11) NOT NULL auto_increment,'
. ' `a_ID` int(11) NOT NULL,'
. ' `title` varchar(255) NOT NULL,'
. ' PRIMARY KEY (`ID`)'
. ' ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT= 0 ;";

?>

jatar_k

6:18 pm on Jan 15, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



if you echo that what does it show?

eelixduppy

6:21 pm on Jan 15, 2007 (gmt 0)



Hello! Try something like this:

$table = "test";
$query = "CREATE TABLE ".$table." (`ID` int(11) NOT NULL auto_increment,`a_ID` int(11) NOT NULL,`title` varchar(255) NOT NULL,PRIMARY KEY (`ID`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0";
[b]//note that I do not have a semi-colon at the end of the query inside the string[/b]
$result = mysql_query($query) or die(mysql_error());
if($result) {
echo 'Table created!';
} else {
echo 'Table died!';
}

A couple things to remember:
*Make sure that the database user has permissions to create tables.
*Make sure that you clean the $table variable if it can be user-defined in any way.

Good luck! :)

HoboTraveler

5:43 am on Jan 16, 2007 (gmt 0)

10+ Year Member



Thanks guys.. Turned out to be an issue with the single quotes.

I removed the quotes and it worked great.

mcavic

8:20 am on Jan 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, the rules that I follow without exception are:

PHP variables, double quotes: $a = "foo";
PHP array keys, single quotes: $a['hi'] = "foo";
MySQL statements, single quotes: WHERE col = 'foo'

That way, there are no conflicts when you say:
$statement = " CREATE TABLE '$table' ... ";