This is the ugliest thing I’ve ever written, but I just don’t know a way to do this otherwise.
The issue is that I need to submit an SQL Query to a database that relies on information extracted from another location using iteration.
EG: I can extract the data with nested for loops, but then need to put an entire row back together to make an insert query for SQL. I tried temporarily storing the cell data in variables and doing it that way, but that also looked awful and didn’t work.
Here is the code I am using now:
Please don’t get mad. I know it’s awful. I want to be better.
On a side note, I’ve taken to calling this line (line 98) the kiloline, because it’s over 1000 characters long.
$res1 = pg_query("INSERT INTO Project_Time_Sheet VALUES ('" .
$objWorksheet->getCellByColumnAndRow(0, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(1, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(2, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(3, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(4, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(5, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(6, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(7, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(8, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(9, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(10, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(11, $row)->getFormattedValue() . "', '" .
$objWorksheet->getCellByColumnAndRow(12, $row)->getFormattedValue() . "')");
Please show me a better/more elegant/not asinine way to do this.
So, I’m going to try directly improving the assembly of this statement. This might not completely answer your question, but it should at least push you down the right path.
Now, doesn’t that look better? No? Slightly more horrifying? Sorry.
Assumption: You’ll always call
getCellByColumnAndRowwith a number as the first parameter, it will always start with 1, and may end at any point. Instead of building the SQL like that, use a loop to gather your data first…Now you can just glue together the array.
Hmm.
getFormattedValueis SQL-safe, right? What if it wasn’t?There’s still some improvement to be made. PostgreSQL supports prepared statements. It might be wise to use them here.
Again, let’s blindly assume that things are moderately dynamic. PHP’s PG extension uses a non-standard placeholder, which makes our life more difficult. Let’s make a small change to the data gathering:
The array is now keyed, using PG’s prepared statement placeholders.
We’ll now reassemble the SQL using the keys instead of the values:
$sqlnow looks something likeLet’s prepare and execute!
Prepared statements get us two things: