I have a function that concatenates a query from POST variables, I do this with a foreach:
$id = $_POST['empId'];
$query = "UPDATE userInfo SET ";
foreach ($_POST as $key => $value) {
$query .= "$key = '$value', ";
}
$query .= " WHERE id = '$id'";
How can I know when the last iteration is, in order to remove the final comma and thus be able to build the query correctly?
You can achieve what you want with the function
implode
, instead of concatenating to the string add elements to an array and finally do aimplode
As a separate note, it seems that you are exposed to a SQL Injection attack , in this post we talk extensively about how to avoid it: How to avoid SQL injection in PHP?
You can use the php end() array function . The function, as you can read in the link, sets the pointer to the last element of the array. If you evaluate it with a conditional, you can achieve what you propose in a fairly clean and efficient way;
It's simple, you just have to consult the keys of the array and then check if you are actually in the last one
Update 2020. PHP 7.3 or higher introduces the functions
array_key_first()
Gets the first key of the given array without affecting the internal array pointer.
array_key_last()
Gets the last key of the given array without affecting the internal array pointer.
Example getting the last iteration, given an array called
$array
: