fryser_d
(Fryser D)
December 9, 2014, 6:20am
1
It’s pretty simple and straight forward:
$id = 1002;
$tableName = "stock";
$idName = "stock_id";
$storeName = "db";
//Create statement.
$sql = 'SELECT *
FROM :tableName
WHERE :idName = :id
LIMIT 1';
//Create command.
$command = Yii::app()->$storeName->createCommand($sql);
//Bind all my parameters.
$command->bindParam( ":tableName", $tableName, PDO::PARAM_STR );
$command->bindParam( ":idName", $idName, PDO::PARAM_STR );
$command->bindParam( ":id", $id, PDO::PARAM_INT );
//Execute query
$model = $command->query();
I get:
[color="#FF0000 "]CDbException[/color]
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '‘stock’
WHE’ at line 2. The SQL statement executed was: SELECT *
FROM :tableName
WHERE :idName = :id
LIMIT 1
I don’t get it, I checked online for the syntax and exemples, I tried permutations with bindValue()… Still same error.
Any idea!?
negar
(Nar8591)
December 9, 2014, 6:27am
2
hi
use this code
//Create statement.
$sql = 'SELECT *
FROM '.Stock::model()->tableName().'
WHERE :idName = :id
LIMIT 1';
i hope useful
fryser_d
(Fryser D)
December 9, 2014, 6:53am
3
Thank you for your answer. But all this goes into a REST API so I want to keep everything as dynamic as I can. So dynamic query and without ActiveRecord for now…
Either way it doesn’t change the nature of the problem. Please note that:
$sql = 'SELECT *
FROM $tableName
WHERE $idName = $id
LIMIT 1';
Works flawlessly, but is a big security hole.
The [color="#0000FF "]$command->bindParam( ":id", $id, PDO::PARAM_INT );[/color] WORKS
but
[color="#0000FF "]$command->bindParam( ":idName", $idName, PDO::PARAM_STR );[/color]
OR [color="#0000FF "]$command->bindParam( ":tableName", $tableName, PDO::PARAM_STR ); [/color]
For some reason give me problems