I'm trying to do this:
- Getting user's ID based on his email name.
- Using that
user_id
to check all his emails that have been sent for him so far.
// db connection here
$sth = $dbh_conn
->prepare("SELECT id FROM users WHERE email = ?")
->execute(array($email));
$num_rows = $sth->fetch(PDO::FETCH_ASSOC);
if($num_rows) {
$user_id = $num_rows['id'];
$stmt = $dbh_conn
->prepare("SELECT 1
FROM ( SELECT count(*) AS num_week,
sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 day))) as num_day,
sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 hour))) as num_hour,
sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 minute))) as num_1min
FROM resend_pass
WHERE user_id = ?
AND date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK))
) a
WHERE num_week < 12 AND num_day < 6 AND num_hour < 4 AND num_1min < 1;")
->execute(array($num_rows['id']));
$result = $stmt->fetchColumn();
if ( $result ) {
echo 'send email';
} else {
echo 'you have sent lot of requests to reset your password. try it later';
}
} else {
echo 'invalid email address';
}
My code works as well. I guess it can be better.
Here is my table's structure:
// users +----+--------+----------------------+------------+ | id | name | email | date_time | +----+--------+----------------------+------------+ | 1 | Jack | [email protected] | 1467911301 | | 2 | John | [email protected] | 1467920198 | | 3 | Peter | [email protected] | 1467933196 | +----+--------+----------------------+------------+ // resend_pass +----+---------+-----------------+------------+ | id | user_id | token | date_time | +----+---------+-----------------+------------+ | 1 | 3 | 8u2934hfr43... | 1467922396 | +----+---------+-----------------+------------+
And I'm trying to follow this rule:
Basic rule of thumb: anytime you have nested queries in a loop, and inner loop is using data from the outer loop, you should re-write as a single joined query.
Do you have any advice?