PHP variables and query
I'm a little confused about this: can I use PHP variables in a pg request?
$conn = pg_pconnect("...");
$a = 1
$b = array ("....")
$c = array ("....")
$d = array ("....")
$i = $a
$ct = "CREATE TABLE $a
(
$b[$i] bigint,
$c[$i] bigint,
$d[$i] bigint
)";
pg_query($conn, $ct);
$result = pg_query($conn, $ct);
if ($result) {$a = $a++}
Will it be able to create 10 tables if I loop it 10 times? Thank!
If you want your strings to be suitable identifiers for PostgreSQL (mixed cases? Reserved words?) And protect against SQL injection at the same time, enter pg_escape_identifier()
:
$ct = 'CREATE TABLE ' . pg_escape_identifier($a) . '(
' . pg_escape_identifier($b[$i]) . ' bigint,
' . pg_escape_identifier($c[$i]) . ' bigint,
' . pg_escape_identifier($d[$i]) . ' bigint
)';
Unless, of course, your identifiers are already prepared.
source to share
Can PHP variables be used in a request?
Apparently you can't. SQL query executed by a SQL server that knows absolutely nothing about PHP.
However, you can add any numeric variables to the PHP string. Which can be sent to the SQL server. But, of course, it won't have any variables, just plain text.
PHP string syntax rules are explained here
For debugging purposes, you can take advantage of PHP strings to be able to print them out.
Just echo
enter your string and see what you have and if it looks like a valid SQL query. If not, correct the code.
source to share