Skip to content

Instantly share code, notes, and snippets.

@nenodias
Last active October 7, 2022 01:58
Show Gist options
  • Save nenodias/f619abefebf513bec30cc781d198e73e to your computer and use it in GitHub Desktop.
Save nenodias/f619abefebf513bec30cc781d198e73e to your computer and use it in GitHub Desktop.
Cron em php
<?php
function limparRegistrosDestaque($db){
$stmt = $db->prepare("UPDATE produtos SET todays_deal=?");
return $stmt->execute([0]);
}
function buscarRegistrosAleatorios($db, $quantidade){
$stmt = $db->prepare("SELECT * FROM produtos ORDER BY rand() limit $quantidade");
$stmt->execute();
$result = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($result, $row);
}
return $result;
}
function atualizarDestaques($db, $registros){
$ids = array_map(function($i){
return $i["id"];
}, $registros);
if(count($registros) > 1){
$sql = "UPDATE produtos SET todays_deal=1 WHERE 1 <> 1";
foreach($ids as $id){
$sql .= " OR id = ? ";
}
$stmt = $db->prepare($sql);
return $stmt->execute($ids);
}
}
try{
$username = "root";
$password = "";
$dbname = "banco";
$conexao = new PDO('mysql:host=localhost;dbname='.$dbname, $username, $password);
limparRegistrosDestaque($conexao);
$registros = buscarRegistrosAleatorios($conexao, 2);
atualizarDestaques($conexao, $registros);
echo 0;
}catch(Exception $e){
error_log($e);
echo 1;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment