Pete
Pete

Reputation: 33

Use php variable in sql statement with concatenation

I have a variable below (storecode) which is getting it's value from the user's input (120)

$storecode = $_POST['storecode'];

The sql which works otherwise in PL/SQL Developer is Select mydate from tbl_store@rm_database.p120081;

I am trying to put the $storecode variable in replacement of the "120" and then concatenate "081" so I have:

 " SELECT mydate from tbl_store@rm_database.p'$storecode'" "081";

Obviously the above is wrong and wanted some guidance to fix this

Upvotes: 2

Views: 1084

Answers (2)

domwrap
domwrap

Reputation: 443

The single-quotes in your expression are being added to the tablename so, assuming $storecode = 120, this statement:

 "SELECT mydate from tbl_store@rm_database.p'$storecode'081";

... results in a literal tablename of tbl_store@rm_database.p'120'081

You can concatenate as suggested in the other answers; however, you can achieve the same result within the string definition with knowledge of variable parsing (look for Simple Syntax under Variable Parsing section).

 "SELECT mydate from tbl_store@rm_database.p{$storecode}081";

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

Without the braces, the parser would try to reference variable $storecode081.

So you were on the right lines originally, you just needed the brace syntax rather than single-quotes.

Upvotes: 0

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

You can create a new variable table_name and add your concatenated databasename.tablename to that variable like

var table_name = 'tbl_store@rm_database.p'.$storecode.'081'

Then in your query you can use this variable as

"SELECT mydate from ".$table_name;

I m not php developer this is just for idea i m sharing the code based on my basic knowledge of php, so you would require to solve syntactical error.

Upvotes: 1

Related Questions