In short: db_query of a SELECT statement is returning no results. However, running the SELECT statement in phpMyAdmin vs the database returns thousands of results. I'm using Drupal 6.
What I'm trying to do: The site I'm working on gets thousands of spammers hitting it each day and creating accounts. The accounts are worthless to them, because if they do not pay, they don't get to do anything but log in. I want to safely remove these accounts. Therefore, I'm selecting the accounts based on certain criteria and then want to iterate through each and use the Drupal delete user function to remove the user from Drupal. Right now, I'm just trying to print the info that returns so I can see if I get the correct results before moving on to the delete, which is a simple 1 line addition.
Here's the code:
include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";
$results = db_query($query);
print $query;
print "<br/>";
print db_num_rows($results);
foreach ($results as $row) {
print "<br />";
print "ID: " & $row['id'];
print "Name: " & $row['name'];
print "E-Mail: " & $row['email'];
print "Role: " & $row['role'];
print "Created: " & $row['created'];
print "Deadline: " & $row['deadline'];
}
For Posterity's (and other people finding this question) sake, here's the final code:
include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";
$results = db_query($query);
print "Users To Delete: " . db_affected_rows($results);
while ($row = db_fetch_array($results)) {
print "<br />";
print "Deleting: ";
print " ID: " . $row['id'];
print " Name: " . $row['name'];
print " E-Mail: " . $row['email'];
print " Role: " . $row['role'];
print " Created: " . $row['created'];
print " Deadline: " . $row['deadline'];
//delete the spam user cleanly
user_delete(array(), $row['id']);
print " Completed.";
}
I setup a CRON job to run this weekly to do the clean-up. There's no reason it can't be run more or less often, though.
&
is a logicalAND
in PHP, for string concatenation you should use.
, e.g.print "ID: " . $row['id'];