Skip to main content

Drupal PHP Snippet: Delete users with no nodes

Here's a handy PHP snippet to purge user accounts for all users who haven't created any nodes on your site. It's useful when you have a lot of users who have signed but haven't created any nodes.

<?php
  // Get a list of all users in the site who have not created any nodes, AND uid > 1
  $sql = "SELECT u.uid FROM {users} u WHERE u.uid NOT IN (SELECT DISTINCT n.uid FROM {node} n) AND u.uid > 1 ORDER BY uid";
  $result = db_query($sql);
  while($row = db_fetch_object($result)) {
  // delete the user account
  user_delete(array(), $row->uid);
}
?>

Works but times out with many users

Snippet works good, but if there is a lot of cleaning up to do it times out and you see a blank page. If you add a LIMIT you could delete it batchwise.

Good point

Thanks for the suggestion. Yes, you have to be careful that the processing time doesn't exceed your PHP timeout values.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <h3> <h4> <br> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options