我正在尝试使用php和mysql制作一个点击计数器

l0oc07j2  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(259)
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
    $date_today = date('Y-m-d');
    $somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");
    mysqli_query($conn, $somecount);
}

?>

<form method="post" action="some.php">
    <input type="submit" name="abc">
</form>

我试过这个密码。有人请帮我计算一下用户点击按钮或提交输入标签。提前谢谢。

7kjnsjlb

7kjnsjlb1#

我建议避免重复密钥更新,而是使用稍微不同的逻辑:

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
    $date_today = date('Y-m-d');
    $selectStatement = "SELECT somecount FROM sometable WHERE today = '".$date_today."'";
    $selectResult = mysqli_query($conn, $selectStatemnt);
    $finalStatement = "";
    if($selectResult){
        $finalStatement = "UPDATE sometable SET somecount = somecount + 1 WHERE today = '".$date_today."'";
    }
    else{
        $finalStatement = "INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', 1)";
    }
    mysqli_query($conn, $finalStatement);
}

?>

<form method="post" action="some.php">
    <input type="submit" name="abc">
</form>

在这里,我们首先检查表中是否已经存在今天的行。如果是这样,只需增加它,否则创建一行并将计数值设置为1。

bq9c1y66

bq9c1y662#

只要更新这行:从

$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");

$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '1') ON DUPLICATE KEY UPDATE somecount=somecount+1");

另外,要确保您没有重定向到当前页面本身所在的另一个页面,请执行以下代码:

<form method="post" action="">
    <input type="submit" name="abc">
</form>

这样做将确保您将提交到同一页。

相关问题