3

I'm a bit confused with this: can I use PHP variables in a pg query?

$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 this be able to create 10 tables if I loop this 10 times? Thanks!

2
  • What library are you using (pg_query, etc.)? Commented Mar 23, 2012 at 13:43
  • @EvanMulawski I'm using Postgres. Sorry for forgetting to mention that at the start. Commented Mar 23, 2012 at 16:17

5 Answers 5

1

If you want to prepare your strings to to be suitable identifiers for PostgreSQL (mixed case? reserved words?) and safeguard against SQL injection at the same time, throw in a 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 prepared already.

Sign up to request clarification or add additional context in comments.

Comments

1

Of course you can, but you have to escape them:

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

Comments

0

It'll 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
)";

Comments

0

"can I use PHP variables in a query?"

Yes, the query is just a string that's being passed to a function. You can do all of the string manipulation and concatenation that you could do with any other variable, before passing it to the function.

Comments

0

can I use PHP variables in a query?

Apparently you can't.
SQL query being executed by the SQL server which knows absolutely nothing of PHP.

However, you can add any number variables into a PHP string. Which can be sent to the SQL server. But of course there will be no variables in it, but just a plain text.

The syntax rules of PHP strings explained here

For the debugging purposes you may use a great advantage of the PHP strings - the ability of printing them out.
Just echo your string out and see what you got and if it looks like correct SQL query. If not - correct the code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.