Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 965
DirWolf Avatar asked Nov 28 '17 11:11

DirWolf


2 Answers

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

$query = "SELECT * FROM $strTable where '.....';
like image 86
Sam Edward Avatar answered Nov 12 '22 13:11

Sam Edward


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.
like image 1
DigiLive Avatar answered Nov 12 '22 14:11

DigiLive