How to combine table name with variable value in mySQL

I am trying to create dynamic code ready from any table with a specific name, but the difference between each table name is the number that the variable generates: for example:

// the way I get my variable, for example, = 3

$pid = $GLOBALS["localid"]; 

// table name, for example, tablename_3

 $strTable = "tablename_" .$pid; 

// here, what the request should look like

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

I am making a mistake somewhere, but I canโ€™t understand, and appreciate a little help.

+5
source share
3 answers

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

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

Other than comments about do or donโ€™t create your queries like this ...

You do not close quotes properly.

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

it should be:

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

or

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

Do not bind strings with SQL. Try using perhaps a class for each table, so you can parse the tablename variable to create an instance of the class. Inside this object you will have a property with the name of the table. It is very dangerous to form queries the way you do it, there is something called SQL Injection, and such code as a prompt. This code is just a raw sample to learn and develop.

eg:.

 class atable { $tablename = 'tablename'; $pid = null; public function generateSQL() { $sql = "SELECT * FROM {$this->tablename}"; if (!empty($this->pid) { $sql .= " WHERE idcolumn = {$this->pid} "; } public function setPid($pid) { $this->pid = (integer) $pid; } } $class = $_POST['tablename-parameter']; $table = new $class(); $sql = $table->generateSQL(); 

Please read this

0
source

Source: https://habr.com/ru/post/1273719/


All Articles