Page 1 of 1

Dynamic table names in PHP-SQL commands?

Posted: Thu Apr 10, 2003 1:15 pm
by MattSharp
Is it possible to use a variable name as the table name in an SQL command with PHP.

Like:

SELECT * from $table.......

When I tried this I get an error and I am wondering if there is something special I need to do to make this work.

Posted: Thu Apr 10, 2003 1:57 pm
by twigletmac
Could you give us a bit more of your code as if $table is defined it should work.

Mac

Posted: Fri Apr 11, 2003 2:59 pm
by toms100
the sql code you execute upon a mysql database is merely a text string szo can contain variables. try doing something like this

Code: Select all

<?php
$sql = "SELECT * FROM ".$table
echo $sql //just to check that the string is as intended
mysql_query($sql)

?>

Posted: Fri Apr 11, 2003 3:01 pm
by Jim
Yes, this is very possible. I do it all the time. MattSharp just forgot to close his variable, so to speak.

To do what you want, I'd do this:

Code: Select all

<?php

$table = " ";  //Whatever table is.  I'm assuming you'll be using either $_GET or $_POST

$sql = "select * from ".$table."";
$act = mysql_query($sql);

?>
Basically, just enclose the variable in ". ." :D

Posted: Fri Apr 11, 2003 6:14 pm
by McGruff
Be aware of possible security risks if you use variables. It might allow a site visitor to perform queries on any table in your database - set access level = 'admin' in a user table?

You could tighten things up by defining an array of allowed table names (or a text string - whatever) then check that $table is a value in the list before proceeding with the query.

Posted: Sat Apr 12, 2003 4:46 am
by twigletmac
Jim wrote:Yes, this is very possible. I do it all the time. MattSharp just forgot to close his variable, so to speak.
He forgot the semi-colon, which would of course cause a parse error so you can just do:

Code: Select all

$sql = "select * from ".$table;
instead of

Code: Select all

$sql = "select * from ".$table."";
'cause you don't need that empty string at the end.

But if that isn't working then there's obviously something else going on in the code, so the full error and a bit more code would make solving the problem possible.

Mac

Posted: Sat Apr 12, 2003 8:36 pm
by MattSharp
Thanks for all the help guys. I determined the problem to be that I am using it in a function and I forgot about making variables global.

But now upon 2nd thought, this may open up a greater security whole. A global variable use to access a database.