Variables as table name?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Variables as table name?

Post by tomfra »

I want to be able to define a table name prefix so that it's easy to change in the php script. The table name "suffix" / main name should stay the same.

But what is the correct format in the MySQL select?

Let's say that the table name is "pre_tblname". I define $tb_prefix such as:

$tb_prefix = "pre";

Now the SELECT part of the MySQL query should look something like:

Code: Select all

$query = "SELECT * FROM `$tb_prefix_tblname`";
But I know this is not the right format. So how can this be done?

Thanks!

Tomas
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$query = "SELECT * FROM `{$tb_prefix}_tblname`";
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

Thanks, it works :) Now I created one more problem because of it though... When I specify the $tb_prefix variable at the beginning of the script, it is inaccessible from within a while loop which is in a function.

Is it possible to read value of variable from within loop which is placed into a function, if that variable have been specified before / above the function? You know, I am still very much in a newbie mode ;)

Thanks again!

Tomas
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

you need to define that variable as global:

Code: Select all

$foo = 'bar';
function foobar() {
   global $foo; // <=======
   echo $foo;
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$somevar = "jelly";

function somefunc()
{
echo $somevar;
global $somevar;
echo $somevar;
//....
}
Post Reply