如何使用变量搜索特定列数据并更新其列数据

How to search for a specific column data using a variable and update its column data

我正在尝试做的事情:我正在尝试更改 'username' 行下的特定列,其中用户名与 $loginuser var 相同,并更改 speedrunhighscore 将该列中的行转换为新的 speedruhighscore.

问题: 在下面的代码中,有一行我以粗体显示,这就是我试图 运行 更改数据库中的数据但数据库中没有任何变化但回声都是 运行 顺利。

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "smolgames";

    $speedrunhighscore = $_POST["speedrunhighscore"];
    $loginuser = $_POST["loginuser"];

    $conn = new mysqli($servername, $username, $password, $dbname);

    if($conn->connect_error){
        die("connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT username FROM userinfos WHERE username = '" . $loginuser . "'"; 
    $result = $conn->query($sql);

    if($result->num_rows > 0){        
      **$sql3 = "UPDATE userinfos SET speedrunhighscore = (' . $speedrunhighscore . ') WHERE username = '" . $loginuser . "'";**
      echo "updating your new highscore":

                if($conn->query($sql3) === TRUE){
                    echo "your highscore have been updated successfully!";

                }
                else{
                    echo "Error: ". $sql3 . "<br>" . $conn->error; 
                }
    } 
    else{
        echo "no usernames found";

        if($conn->query($sql2) === TRUE){
            echo "new highscore send successfully";
        }
        else{
            echo "Error: ". $sql2 . "<br>" . $conn->error; 
        }
    }   

    $conn->close();
?>

注意:变量 loginuser 从字符串 I post 使用统一 C#

更改

对于初学者,您应该使用带边界占位符的准备好的语句。这可确保您的查询不易受到 SQL 注入攻击,并确保即使是 O'Riley 这样的用户名也能正常工作。

接下来,您不需要在更新之前检查该行是否存在——您可以立即尝试执行更新,并检查实际更新了多少行。

最后,您应该将 MySQLi 连接配置为在出错时抛出异常,这意味着您不必为每个查询进行单独的错误处理。

<?php
// Configure MySQLi to throw exceptions on failure instead 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "smolgames";

$speedrunhighscore = $_POST["speedrunhighscore"];
$loginuser = $_POST["loginuser"];

try {
    $conn = new mysqli($servername, $username, $password, $dbname);

    $stmt = $conn->prepare("UPDATE userinfos
                                SET speedrunhighscore = ?
                                WHERE username = ?");
    $stmt->bind_param("ss", $speedrunhighscore, $loginuser);
    $stmt->execute();
    $affectedRows = $stmt->affected_rows;
    $stmt->close();
    
    if ($affectedRows) {
        echo "your highscore have been updated successfully!";
    } else {
        echo "no usernames found";
    }
} catch (Exception $e) {
    // Handle the exception 
    // Log it, send a message to the user "something went wrong"
}

您应该实施某种身份验证和授权层,因为现在您可以提交其他人的用户名和任意高分,并且您基本上可以更新 table.[=12= 中的任何分数]