I have a query with bound parameters for the values for inserting data into a table. I am using PDO. The idea is that I have an invoice with an order number, date, time, etc. The invoice has a list of products with their quantities, however the # of unique products varies from one invoice to another. As a result that means the # of columns the quantities will be inserted into will vary from invoice to invoice. Invoice A with 4 products will be inserting data into 4 columns vs invoice B with 5 products which will be dealing with 5 products.
$sth = conn->prepare("INSERT INTO test1 (col_1, col_2, col_3) VALUES (:order, :date, :time)");
$sth->bindParam(':order', $orderID);
$sth->bindParam(':date', $date);
$sth->bindParam(':time', $time);
$sth->execute();
This query works and inserts whatever values I have for the variables into the appropriate columns. How can I have the columns function similar to a bound parameter too?
When I tried something like below it did not work.
$sth = conn->prepare("INSERT INTO test1 (:col1, :col2) VALUES (:order, :date, :time)");
$sth->bindParam(':order', $orderID);
$sth->bindParam(':date', $date);
$sth->bindParam(':time', $time);
$sth->bindParam(':col1', $col1);
$sth->bindParam(':col2', $col2);
I made the values for the variables $col1 and $col2 column names names in the test1 table. I came across this post in my search while I tried to solve this issue which helped somewhat.
Can PHP PDO Statements accept the table or column name as parameter?
Part of the issue though is that I don't know how many column names I will be inserting into in advance and the above linked idea seems to only work if you know the # of columns in advance. Any advice on this?