每当有人转到sql中的链接时,如何在mysql数据库中为int添加1

时间:2017-07-18 23:45:25

标签: php mysql

我已经测试了所有内容,这里没有任何作品是我的代码

<?php
session_start();
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { die('Invalid id'); }
$conn = mysqli_connect("redacted", "redacted", "redacted", "redacted");
if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");
?>

在我希望它在用户仪表板上回显后,这就是我所拥有的

<h1>Clicks</h1>
                <br />
                <br />
                You have gotten: <?php $conn = mysqli_connect("localhost", 
"id2278622_jonny", "Fencing1", "id2278622_affiliate");
 if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
$sql = "SELECT clicks FROM affiliate WHERE ID='$ID'";
echo "$sql";
?> Clicks!

但它只是回应了sql代码

2 个答案:

答案 0 :(得分:1)

您实际上没有将查询发送到数据库。您刚刚构建了一个查询字符串。您甚至没有保存到变量的字符串。

$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");

应该是:

$id = (int)$_GET['id'];
$qry= "UPDATE affiliate SET clicks = clicks+1 WHERE ID='$id'";
conn->query($qry);
header("Location: https://discord.gg/CjzZRBq");

您还应该查找SQL Injection。转换为int可以降低风险,但绝对应该使用绑定变量。

答案 1 :(得分:0)

问题是你只是回显$sql(这是查询字符串),而不是将SQL命令传递给你的数据库。另请注意,您当前的脚本容易受到SQL注入攻击。为避免这种情况,请使用 prepared statements

// Retrieve the number of existing clicks
$stmt = $conn->prepare("SELECT clicks FROM affiliate WHERE ID = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($clicks); // Store the result in the $clicks variable

$clicks++; // Increment clicks

// Update the table
$stmt2 = $conn->prepare("UPDATE affiliate SET clicks = ? WHERE ID = ?");
$stmt2->bind_param("si", $clicks, $id); 
$stmt2->execute();

// Close the connection once finished
$conn->close();

希望这有帮助! :)