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!


source to share

5 answers

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.



Of course you can, but you should avoid them:

$ct = "CREATE TABLE $a
{$b[$i]} bigint,
{$c[$i]} bigint,
{$d[$i]} bigint




It will work for $ a, but not for arrays. you should do something like:

$ct = "CREATE TABLE $a
$b[$i]." bigint,".
$c[$i]." bigint,".
$d[$i]." bigint




"Can I use PHP variables in the request?"

Yes, a request is just a string passed to a function. You can do all the string manipulation and concatenation that you can do with any other variable before passing it to a function.



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.



All Articles