I'm checking to see if a value already exists in the DB, if it does I want to just update the last_date
as well as up the count (visit_num
) by 1. I'm not sure if there's a more efficient way to do that than by running a query to retrieve the current number and then doing ++
. This is what I currently have (without retrieving the column).
function subscribe($visit_num, $email, $last_visit_date){
$sql = 'SELECT 1 from `visits` WHERE `email` = ? LIMIT 1';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $email, PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()){
$totalVisits = /*Somehow retrieve the current count*/ + $visit_num;
$query = "UPDATE `visits` SET
`visit_num`=:visit_num,
`last_visit_date`=:last_visit_date
WHERE
`email` = :email";
// prepare query statement
$stmt = $dbh->prepare($query);
// bind values
$stmt->bindParam(":visit_num", $totalVisits);
$stmt->bindParam(":last_visit_date", $last_visit_date);
$stmt->bindParam(":email", $email);
$res = $stmt->execute();
if($res){
$arr = array('message' => 'Added');
echo json_encode($arr);
}else{
$arr = array('message' => "Error");
echo json_encode($arr);
}
}
I can just do (previous to this) a "SELECT COUNT(*) FROM 'visits' WHERE 'email' = '$email'"
and add it but I'm not sure whether that's the best approach or if there's something better.