0

I want a MySQL query with a variable as table. Here is what I'm looking for:

mysql_query("SELECT * FROM $var WHERE $anothervar ='1'"))

How can I do this?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
totallyuneekname
  • 2,000
  • 4
  • 16
  • 27

8 Answers8

3

First of all, stop using mysql_ functions. They have been deprecated. Check out mysqli or PDO.

When using PHP to query the database you can build the entire query as you please. You can type out the full query or add variables for more dynamic queries. What you did is correct (Except for the double parenthese on the right).

<?php
$query = "SELECT * FROM users WHERE id ='1'";

//the above will be the same as

$var = 'users';
$anothervar = 'id';
$query = "SELECT * FROM $var WHERE $anothervar ='1'";

//execute query.
?>

So yes, you can just use a variable table name when constucting a query in PHP. You do need to keep in mind that all the variables you use can lead to SQL injection. So if you are getting the values for table and column names from user input, make sure you validate them properly!

Simply using mysql_real_escape_string() or mysqli_real_escape_string() will not work on table and column names, because they are not enclosed in quotes. My vote would go for a whitelist if you receive user input for columns/tables and are concatenating queries. EG:

<?php
$allowed_tables = array("users", "articles", "messages");

if (!in_array($var, $allowed_tables)) {
  echo 'Invalid table';
  exit();
}
?>

Another good read would be how-to-prevent-sql-injection-in-php which also goes into parameterized queries, which is basically what you want to do, but then in a more secure manner then concatenating strings.

Community
  • 1
  • 1
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
3

Write your sql query as

mysql_query("SELECT * FROM $var WHERE anothervar ='1'");

You have placed extra parenthesis without semicolon, I beleive it welll definitely work.

MMM
  • 7,221
  • 2
  • 24
  • 42
  • 1
    Why is this getting upvotes? The code looks broken... I've added the missing quotation mark. – MMM May 15 '13 at 10:04
1

You're going to hate my answer, but I really believe it's the right one (if not a direct one).

I would avoid this approach if at all possible (or at least make FOR SURE you sanitize your 'inputs'). Without knowing where those variables came from I'd say you've left yourself open to a sql-injection attack. Granted, it's more difficult to create dynamic sql via parameterization, but if you can get around this problem in any other way please do so.

It's much better to have to write a bunch more code or have a solution that isn't so elegant than to have a nice clean codebase and a door wide open giving curious minds access to your dbms.

Also as a practice I'd consider using stored procedures in favor of in-line sql. It will make your sql easier to maintain and offer you better flexibility in the long run. The way to do what you want via a stored procedure would be to build a prepared statement dynamically inside the procedure, but that's going to open you up to the same sql-injection risks as the way you're attempting to do this now.

Dave
  • 900
  • 6
  • 22
  • Alright, I see you did hate my answer, so I'm coming back for more. What you posted is a working solution, so I don't think anyone's sure what you're looking for here. The reason for my answer above is because the way you've implemented this is so obviously going to "work" that I decided to delve deeper into the question of "should" you implement your solution to your problem this way. I think I supported my argument against your design pretty well (and gave a couple suggestions on how to possibly do this better; I did everything but write your code for you), so why the down-vote? – Dave May 16 '13 at 02:36
0

Your query is looking ok. There are just an extra parenthesis. Please try to use below code.

mysql_query("SELECT * FROM $var WHERE $anothervar ='1'");
kwelsan
  • 1,229
  • 1
  • 7
  • 18
0
mysql_query("SELECT * FROM $var WHERE $anothervar ='1'")); // TYPO ERR  ))


mysql_query("SELECT * FROM $var WHERE $anothervar ='1'");

IF $var ,$anothervar have been defined,AND GET ERROR ..TRY

mysql_query("SELECT * FROM `$var` WHERE `$anothervar` ='1'");

** mysqli is good
JOE LEE
  • 1,058
  • 1
  • 6
  • 6
0

In addition to what the other answers have said if $var or $anothervar may be a reserved word in sql then they should be surrounded by backticks.

"SELECT * FROM$varWHERE$anothervar` ='1'"

I agree with @Hugo that you should have a whitelist of allowed values for $var and $anothervar.

Belinda
  • 1,230
  • 2
  • 14
  • 25
-2

If you want to convert array to string in php, use implode(sep,arr) function. If your $var is array of table name or something like that, then:

mysql_query("SELECT * FROM ". implode(',',$var) ." WHERE $anothervar ='1'")

Note: If your table name is the same as keyword in mysql, this code won't work. So, to prevent that, change code like this:

mysql_query("SELECT * FROM `". implode('`,`',$var) ."` WHERE `$anothervar` ='1'")
sreng
  • 153
  • 3
-3

You should use something like this:

mysql_query("SELECT * FROM " . $var . " WHERE " . $anothervar . " ='1'"))
  • 1
    This does exactly the same as the OP:s code, since PHP expands any variables in strings that are surrounded by double quotes. (http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing) – Jens Wegar May 02 '13 at 12:25
  • @JensWegar: have you tried it? it works normally. – urframes May 02 '13 at 12:28
  • There's nothing wrong with the code you posted, it's just that the end result of running your code is exactly the same as the code in the original question. Thus your answer unfortunately does not bring anything new to the table. – Jens Wegar May 02 '13 at 12:47