只需要更新一个元组,但这是更新 table 中的整列

Need to update only one tuple, but this is updating the whole column in table

我先检查 url 是否存在,看看他是否第一次投票,如果是,那么我会将用户声誉添加到已投票的列中,但我只想添加到那个url 不是所有的 url,此代码正在添加到 "upvotes" 列中的所有所有元组,我希望它仅添加到特定的元组。

<!Doctype html>
<html>
<?php
$c=$_GET['a'];// users name
$d=$_GET['b'];// usesrs id
$e=$_GET['c'];//  users repute
$ur=$_POST['url'];

// Create connection
$con=mysqli_connect("localhost","root","","repute system");
    if(mysqli_connect_errno()){
        echo "ERROR ".mysqli_connect_error();
} 

$sql = mysqli_query($con,"SELECT * FROM sites");
if (mysqli_num_rows($sql) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($sql)) 
    {

        if($ur == $row['URL'] && $d != $row['id'])
        {
        $ne = $row['upvotes'] + $e;   
        $sol = mysqli_query($con, "UPDATE sites SET upvotes = $ne ");
        $bew = mysqli_query($con,"INSERT INTO v_sites(teacher_id,URL,vote) VALUES ('$d','$ur','$e')");
        echo "Upvoted the site   ";
        echo $ur;       
       }
    }
} else {
    echo "Sorry before upvoting you have to block it first or you are trying to upvote your own report, in which you cant";
}
?>
</html>

您需要一个 WHERE 子句来匹配 URL:

$stmt = mysqli_prepare($con, "UPDATE sites 
                              SET upvotes = upvotes + 1
                              WHERE url = ? AND id = ?";
mysqli_stmt_bind_param($stmt, "ss", $ur, $d);
mysqli_stmt_execute($stmt);

您不需要 SELECTwhile 循环,因为 MySQL 可以找到匹配的行并自行更新它们。

您也不应该在循环中使用 INSERT 查询,因为它每次都插入相同的行。

并且您应该切换到准备好的语句,如上所示,而不是将字符串插入查询中,因为您的代码会受到 SQL 注入的影响。

正在更新您的所有行,因为您没有使用 where 子句。

UPDATE sites SET upvotes = $ne

应改为:

UPDATE sites SET upvotes = $ne WHERE id='$d'

但是,如果$ne也是一个字符串,那么$ne也应该被引用:

UPDATE sites SET upvotes = '$ne' WHERE id='$d'

继续阅读 UPDATE

"My table's name in sites it has 5 columns, which are URL,status,upvotes,downvotes, id and all are varchar with 30 length"

这告诉我 id 也是 VARCHAR;这不是一个好主意,但这取决于你。如果您的所有 ID 都是基于数字的,那么最好使用 int 进行这样的查询。

这就是为什么需要在 $d 变量周围使用引号 WHERE id='$d' 的原因。


您当前的代码对 SQL injection. Use prepared statements, or PDO with prepared statements 开放,它们更安全