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.
Dynamic table names in PHP-SQL commands?
Moderator: General Moderators
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
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)
?>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:
Basically, just enclose the variable in ". ." 
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);
?>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.
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.
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
He forgot the semi-colon, which would of course cause a parse error so you can just do:Jim wrote:Yes, this is very possible. I do it all the time. MattSharp just forgot to close his variable, so to speak.
Code: Select all
$sql = "select * from ".$table;Code: Select all
$sql = "select * from ".$table."";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