使用提交按钮更新数据库数据

Update database data with submit button

我想用新数据更新数据库,这样当您将文本放入文本框中然后单击提交按钮时,数据将被发送到数据库,并带有特定的 ID。我只想发送亮度,代码如下。当我写这样的东西时,我 运行 它,我收到一个 403 错误:禁止访问。我该如何解决这个问题?

<?php
   function updater($value,$id){
// Create connection
   $conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
// Check connection
   if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }
   $sql = "UPDATE table_name SET name=$value WHERE id=$id";
   if ($conn->query($sql) === TRUE) {
       echo "Record updated successfully";
   } else {
       echo "Error updating record: " . $conn->error;
   }
//$conn->close();
}
?>

<!DOCTYPE html>
<html>
<header>
</header>
<body>
    <form action="<?php updater($_POST['name'],1); ?>" method="post" style="height:50px;width:50px;">
        <input type="text" name="name" /><br><br>
        <input type="submit" /><br/>
    </form>
</body>
</html>

您需要将 URL 放在进行表单处理的 action 属性中,而不是函数中:

action="<?php updater($_POST['name'],1); ?>"  // not this
action="<?php echo $_SERVER['PHP_SELF']; ?>" // path to this page

如果这是在同一页面上,您可以省略它或使用 $_SERVER['PHP_SELF'],然后抓取表单提交。在该过程中,然后调用您的自定义函数。

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $value = $_POST['name'];
    $id = 1;

    updater($value, $id);
}

一个简单的解决方法就是引用其中的字符串:

$sql = "UPDATE table_name SET name='$value' WHERE id=$id";

但这对SQL注入是开放的,另一种更安全查询的方法是准备它们:

function updater($value,$id) {
    // Create connection
   $conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
    // Check connection
   if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }
   $sql = "UPDATE table_name SET name = ? WHERE id= ?";
   $update = $conn->prepare($sql);
   $update->bind_param('si', $value, $id);
   $update->execute();
   if ($update->affected_rows > 0) {
       echo "Record updated successfully";
   } else {
       echo "Error updating record: " . $conn->error;
   }
}

像这样:

<?php
function updater($value,$id){
    // Create connection
    $conn = new mysqli( 'localhost' , 'user_name' , 'pass' ,'data_base_name' );
    $value =mysqli_real_escape_string($conn,$value);
    $id =mysqli_real_escape_string($conn,$id);
    // Check connection

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }   
    $sql = "UPDATE table_name SET name='{$value}' WHERE id='{$id}'";
    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }
    $conn->close();
}   

if(isset($_POST['name'])){
    updater($_POST['name'],$_POST['id'])
}
?>

<!DOCTYPE html>
<html>
<header>
</header>
<body>
<form action="" method="post" style="height:50px;width:50px;">
    <input type="hidden" name="id" value="1" />           
    <input type="text" name="name" /><br><br>
    <input type="submit" /><br/>
</form>
</body>
</html>