I have an array of column headers and an array of corresponding values at the same index
I need to update a row using both those arrays in SQL.
I know this might not be the neatest way of doing this. How I’ve got the values is I take the SQL database columns and use those to generate an HTML form which gives the values hence why both are in an array.
Using an INPUT my SQL looks like this and works how I want it to:
$strcol = implode(",", $fieldname);
$strdata = implode(",", $fielddata);
$placeholders = str_repeat(" ?, ", count($fielddata)-1) . "?";
print_r($placeholders);
$sql = "INSERT INTO morning (" . $strcol . ")
VALUES (". $placeholders . ")";
print_r($sql);
$result = $conn->execute_query($sql, $fielddata);
That gives a result something like:
BUT I can’t figure out how to do the same with an UPDATE
, I might have missed a really obvious solution somewhere
2
Answers
Explanation:
(‘id’) in the $fieldname array. It uses the array_search function to
find the index.
array, an error message is printed, and the script exits. You should
handle this error according to your application’s requirements.
the $fielddata array using the $idKey index.
statement. It iterates over the $fieldname array using array_map and
generates column-value pairs formatted as "column = ?".
$assignments variable for the SET part and the primary key for the
WHERE clause.
$conn->execute_query() method. The $fielddata array is merged with an
array containing only the primary key value for parameterized query
execution.
Hopefully, You enjoyed the explanation.