Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

c4ost's avatar
Level 2

Query builder and multiple queries advice needed

Hello there! I'm making my query builder, code runs and works perfectly but I need an advice. Here's my code:

// method for updating a single record in database in query builder

public function update($table, $values, $filter)
    {
        $statement = $this->pdo->prepare("update {$table} set " .
        implode('=?, ', array_keys($values)) . "=? " .
        "where " . implode('=?, ', array_keys($filter)) . "=?");

        $statement->execute(array_values(array_merge($values, $filter)));

    }

I use this method in my update page, where I update multiple records in table if they're changed. For example I have this html form inside table:

    <form class="" action="update" method="post">
      <?php foreach($tasks as $task): ?>
        <tr>
          <td><?= $task->id?></td>
          <td><?= $task->description ?></td>
          <td>
            <input type="checkbox" name="task_status[]" value="<?= $task->id ?>"
            <?= $task->completed == 1 ? "checked" : "" ?>/>
          </td>
        </tr>
      <?php endforeach; ?>
      <button type="submit" name="button">submit</button>
    </form>
	<!-- Outputs table items and checkboxes to track progress in a form-->

Controller code:

// fetch everything related to id from table
$id = $app['database']->selectBatch('todos', 'id');

// for each id fetched if this id present in request then set this value to corresponding bool
foreach($id as $value)
{
  if(!in_array($value->id, $_POST['task_status']))
  {
    $app['database']->update('todos',
    ['completed' => 0],
    ['id' => $value->id]
    );
  } else {
    $app['database']->update('todos',
    ['completed' => 1],
    ['id' => $value->id]
    );
  }
}

header("Location: home");

My concern is in the last snippet, isn't that resource consuming to loop over all db id's each time update controller is fired? Or is it okay? I just don't know how to check if values were unchecked, because in 'task_status' array - only checked ones are passed to request.

0 likes
1 reply

Please or to participate in this conversation.