What is the best practise to move for multiple foreach statements to an array? I am repeating the process in my code, when I know there is a better and faster way to do this. Is it possible to isset
the foreach
? I am starting to work with PDO
, how would I shorten my below code or move it into an array of some type?
if (isset($_POST['one'], $_POST['two'], $_POST['three'])) {
foreach($_POST['one'] as $id => $one) {
$sql = "UPDATE table SET one = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($one, $id));
}
foreach($_POST['two'] as $id => $two) {
$sql = "UPDATE table SET two = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($two, $id));
}
foreach($_POST['three'] as $id => $three) {
$sql = "UPDATE table SET three = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($three, $id));
}
}
EDIT: An example of the HTML/PHP (input type='text') for a more clear example:
$stmt = $db->query('SELECT * FROM table ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "
<input type='text' id='one' value='{$row['one']}' name = 'one[{$row['id']}]' />
<input type='text' id='two' value='{$row['two']}' name = 'two[{$row['id']}]' />
<input type='text' id='three' value='{$row['three']}' name = 'three[{$row['id']}]' />";
}