1

I'm having trouble figuring out how to get the number of affected rows from an update query in Drupal.

I have a form where users can update their profile details. Now, not every user is going to update everything from their profile. They may just update one field or two.

How do I account if there was a change or not and check for the affected rows?

This is the code I am running.

$update_query = $db->update('TABLE NAME')
  ->fields([
    'uid' => $uid,
    'name_of_user' => $name,
    'url' => $url,
    'website' => $website,
    'industry' => $industry,
    'company_size' => $companySize,
    'company_type' => $companyType,
    'headquarters' => $headquarters,
    'founded' => $founded,
    'page_picture' => $upload_picture,
    'tagline' => $tagline,
    'updated_at' => $time,
  ])
  ->condition('uid', $uid);

  $affectedRows = $update_query->execute()->rowCount();
  return new AjaxResponse($affectedRows);

The code doesn't return anything. I even checked the network tab and there's nothing displayed in the response tab. I should be getting back either 0 or 1. Am I missing something?

1

$update_query->execute()->rowCount() would cause a Call to a member function rowCount() on a non-object (or Call to a member function rowCount() on int, on PHP 7.4) since $update_query->execute() returns the number of rows matched by the update query, including the ones that actually didn't have to be updated.
rowCount() can be called only when execute() returns an object implementing StatementInterface, which is the case for Select::execute(), Truncate::execute(), Upsert::execute(), and Query::execute().

Unfortunately, the only way to get the number of rows changed from an update query is to fetch the rows matching the update condition (in your case, the rows for which uid is equal to $uid), and count which rows have, for the desired fields (in your case, name_of_user, url, website, industry, company_size, company_type, headquarters, founded, page_picture, tagline, and updated_at), a value different from the value set by the update query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.