Forum Moderators: coopster

Message Too Old, No Replies

Create mysql table name using php variable

How to ...

         

kaz

11:43 pm on Jun 26, 2008 (gmt 0)

10+ Year Member



I have written the following code which creates a table

 $review = 'CREATE TABLE reviewtablename (
q1 VARCHAR( 150 ) NOT NULL,
q2 SMALLINT( 3 ) DEFAULT 0 NOT NULL,
q3 SMALLINT( 3 ) DEFAULT 0 NOT NULL,
q4 SMALLINT( 3 ) DEFAULT 0 NOT NULL
)';
mysql_query( $review );

I have tested and verified the above code creates a table as I intended.

I would like to do the following though. Instead of the table name being called reviewtablename I would like to use an existing variable $business_id

I'm stuck on what seems should be simple inserting the php variable into the mysql statement. Can anyone help me along, and any advice on how single, double quotes, / ( work in these statements would help also if you have time. Thank you in advance.

eelixduppy

5:12 am on Jun 27, 2008 (gmt 0)



Try the following:

$review = 'CREATE TABLE `' . $business_id . '` (
q1 VARCHAR( 150 ) NOT NULL,
q2 SMALLINT( 3 ) DEFAULT 0 NOT NULL,
q3 SMALLINT( 3 ) DEFAULT 0 NOT NULL,
q4 SMALLINT( 3 ) DEFAULT 0 NOT NULL
)';

There are two things to notice here. One, the concatenation of the variable into the string, using the period (.) to do so. You can find more information on that in the String [us2.php.net] documentation.

The other thing to note, which is actually pretty important, is the prime character(`) that I've added around the table name. This escapes the table name in MySQL just in case you happen to use a reserved word [dev.mysql.com] for the table name. While this isn't suggested, it can and does happen so we add the escape character in there just in case :)

One last note about security. One, you definitely want to know that this variable is going to contain something you want it to contain. I don't know how you are setting this up, but you still want to make sure. This can be checking it against an array of potential names, or whatever. As long as someone isn't injecting data into the variable when you aren't aware of it you'll be fine. With that being said, make sure that you don't have register globals turned on in your php.ini config file. This can lead to other potential attacks if you don't initialize the $business_id variable before you use it in your query. Just a few things you should look into to be more safe :)

Good luck

kaz

5:24 am on Jun 27, 2008 (gmt 0)

10+ Year Member



Cheers. That did work.

I appreciate the extra info, very helpful. Regarding security, i follow you, the variable used for the table name is pulled from an auto-incremented field in another table