0
$hr = '12';

$q = 'INSERT INTO table_value (date_recorded, day, $hr) VALUES(:a, :b, :c)';

Is it possible to define a column as a variable in an insert query for php pgsql?

Qirel
  • 25,449
  • 7
  • 45
  • 62
Paul Kiarie
  • 37
  • 1
  • 8
  • 2
    Well, yes - the SQL is just a string from PHP - but it can be opening a can of worms, that variable should never under any circumstance be user input. Usually column-names can't be purely numeric though. – Qirel Mar 04 '20 at 08:20
  • 1
    Column name `12`? – u_mulder Mar 04 '20 at 08:20
  • 1
    Also relevant here https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – Qirel Mar 04 '20 at 08:20
  • @u_mulder [why not ?](https://www.db-fiddle.com/f/ksj3uyxz5ogheQNnCUXr2e/0) :p – Cid Mar 04 '20 at 08:23
  • yes the column is 12 but can change it to something like _12 – Paul Kiarie Mar 04 '20 at 08:25
  • Nothing stops you from creating the string containing the query with anything from variable. However, you can't use prepared statements to define table or column names. `INSERT INTO :tablename (:colname) VALUES (...)` won't work – Cid Mar 04 '20 at 08:27
  • As @Qirel has pointed out, it will work, although you won't get any variable substitution if you use single quotes around the string, and you will need to enclose the value in double quotes if it's a number like `12`. e.g. `$q = "INSERT INTO table_value (date_recorded, day, \"$hr\") VALUES(:a, :b, :c)";` – Nick Mar 04 '20 at 08:30
  • Thanks guys , this for @Nick worked like charm! – Paul Kiarie Mar 04 '20 at 11:19
  • @PaulKiarie good to hear you got it working. – Nick Mar 04 '20 at 11:20

0 Answers0