0

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']}]' />";
} 
4

2 回答 2

3

Assuming all the inputs will have the same IDs:

$sql = "UPDATE table set one = :one, two = :two, three = :three where id = :id";
$q = $db->prepare($sql);
$q->bindParam(':one', $one);
$q->bindParam(':two', $two);
$q->bindParam(':three', $three);
$q->bindParam(':id', $id);
foreach ($_POST['one'] as $id => $one) {
    $two = $_POST['two'][$id];
    $three = $_POST['three'][$id];
    $q->execute();
}

You should only prepare the statement once, not every time through the loop. And by using bindParam you can bind all the parameters to variable references. You can then set all the variables in one loop, and execute the query with those values.

于 2013-10-02T20:22:20.763 回答
0

Another way to do this:

<?PHP
foreach($_POST as $name => $value) {
    if(isset($name,$value)){
        $sql = "UPDATE table SET $name = $value WHERE id = $name";
        $q->execute($db->prepare($sql)); 
    }
}
?>

If you're posting other information too, you can move this into an array. Then have

foreach($_POST[fieldsToUpdate] as $name => $value) {

Let me know if you have further questions.

于 2013-10-02T20:33:40.223 回答