Page 1 of 1

Variables within SQL

Posted: Wed May 12, 2010 9:01 pm
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

Re: Variables within SQL

Posted: Wed May 12, 2010 9:30 pm
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

Re: Variables within SQL

Posted: Wed May 12, 2010 9:54 pm
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

Re: Variables within SQL

Posted: Wed May 12, 2010 10:08 pm
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

Re: Variables within SQL

Posted: Thu May 13, 2010 8:14 am
by gamesmad
Thank you so much :)

-Will