DirWolf
DirWolf

Reputation: 891

How to Concatenate table name with with a variable value in mySQL

I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :

//that's how I get my variable the value for example is = 3

$pid = $GLOBALS["localid"];

//the table name for example is tablename_3

$strTable = "tablename_" .$pid;

//here's how the query should look like

$query = "SELECT * FROM . $strTable . where .....;

I'm making a mistake somewhere but can't figure it out and would appreciate a little help please

Upvotes: 5

Views: 2200

Answers (2)

Sam Edward
Sam Edward

Reputation: 309

Remove the dots and also make sure you have single quotes aroung where

$query = "SELECT * FROM $strTable where '.....';

Upvotes: 3

DigiLive
DigiLive

Reputation: 1103

Besides the comments about do or don't build your queries like this...

You're not closing the quotes properly.

$query = "SELECT * FROM . $strTable . where .....; //Double quote not closed.

should be:

$query = 'SELECT * FROM' . $strTable . 'where .....'; //Single quoted strings concatenated with variable.

or

$query = "SELECT * FROM $strTable where ....."; //Variable inside double quoted string.

Upvotes: 1

Related Questions