[英]PHP MySQL Update after Seconds
當網站打開X秒后,我想更新一個MySQL字段。 我從MySQL獲取Seconds / Time,並且想在秒數結束后在MySQL中進行更新。
我試過了
sleep($adddisplaytime);
但隨后站點等待完成,並且不會首先運行
打開網站幾秒鍾后,有什么方法可以運行我的更新嗎?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
可以在PHP或MySQL中
注意:這將完成您想要的操作,但是可能會被反復擊中AJAX端點的人利用,因此您需要為它建立一些保護。
您將需要一個附加的PHP文件,該PHP的工作是僅更新數據庫。 您將需要從頁面加載腳本中取出該更新。
您的HTML / JS / PHP初始加載
<script>
setTimeout(function() {
$.ajax('/your/ajax/endpoint.php', {
data: {
'adid': 'your id'
/*
If this is in your PHP file, you can echo the ID straight there.
Not totally recommended, but that's one way An additional /
better way is to add it to a div with a data attribute and
use jQuery to select the data off of there
*/
}
}); // Probably lots more you can do here, but in this case, for simplicity, just sending and that's it
}, 2000); // This will do a 2 second wait
</script>
您的新附加PHP文件位於/your/ajax/endpoint.php
<?php
// THIS FILE DOES THE UPDATE
$adid = $_POST['adid'];
// As mentioned by tadman in his comment.. I would use prepared statements
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = ?";
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare($query1);
$sth->execute(array($adid));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
注意:
再次,為了安全起見,您真的要考慮讓第一個PHP腳本生成一個唯一ID(並將其存儲在db中),並將其傳遞到頁面,並讓AJAX將該唯一ID與adid一起發送,如果您提供的唯一ID僅在數據庫中,然后您才能知道這是合法請求。 從數據庫中刪除唯一ID,然后進行更新。
如果要在打開頁面后等待幾秒鍾,然后運行update語句,請在頁面頂部編寫以下代碼:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.