Variables within SQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gamesmad
Forum Newbie
Posts: 3
Joined: Wed May 12, 2010 8:58 pm

Variables within SQL

Post by gamesmad »

Hey,

Just wondering if anyone can correct the way I am using variables in the SQL?

CREATE TABLE $id . _example LIKE default_example;

I'm trying to use $id as the table prefix.

-Will
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Variables within SQL

Post by califdon »

I've never seen SQL syntax like that, I don't think it's even close to being valid.

If you want to learn how to create a table structured like another table, read this: http://www.techonthenet.com/sql/tables/ ... table2.php
gamesmad
Forum Newbie
Posts: 3
Joined: Wed May 12, 2010 8:58 pm

Re: Variables within SQL

Post by gamesmad »

The syntax is valid, heres an example - http://www.electrictoolbox.com/copy-tab ... able-like/

For example if a variable ($id) is set to "test", I want the SQL command to be sent as -

CREATE TABLE test_example LIKE default_example;

I am trying to use -

CREATE TABLE $id . _example LIKE default_example;

But it's not working, what is the correct method?

-Will
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: Variables within SQL

Post by mikosiko »

yup... talking at SQL level the syntax is correct in regarding to the "LIKE" usage... but a variable can not be used to define the name of an object in that way... only way that I'm aware of is using user variables in a "prepared" statement... examples here:

Code: Select all

http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
and here http://www.ultramegatech.com/blog/2009/ ... nts-in-php/ you will find some examples

now... directly in PHP you can use something like this:

Code: Select all

  $Id = 'tbl_';
  $sql = "CREATE TABLE ". $Id ."_articles LIKE articles";
  $rs = mysql_query( $sql );
Edited to add information
gamesmad
Forum Newbie
Posts: 3
Joined: Wed May 12, 2010 8:58 pm

Re: Variables within SQL

Post by gamesmad »

Thank you so much :)

-Will
Post Reply