当网站打开X秒后,我想更新一个MySQL字段。 我从MySQL获取了Seconds / Time,并且想在秒数结束后在MySQL中进行更新。
我尝试过
sleep($adddisplaytime);
但是网站等待完成,并且没有先运行
打开网站几秒钟后,是否可以运行我的更新?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
可以在PHP或MySQL中使用
答案 0 :(得分:0)
注意:这会做您想要的,但是可能会被反复击中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,然后进行更新。
答案 1 :(得分:-2)
如果要在打开页面后等待几秒钟,然后运行update语句,请在页面顶部编写以下代码:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");