表单提交时php数据库没有更新

时间:2018-04-06 03:54:28

标签: php

我正在尝试编写一个PHP代码来通过表单更新数据库,但是,数据似乎永远不会通过数据库!我的代码如下(只是为了让您知道HTML代码开头上方的PHP代码位于一个名为post.inc.php的单独文档中):

4/6/2018 10:32:15
4/6/2018 10:33:32
4/6/2018 10:38:32
4/6/2018 10:43:32
4/6/2018 10:48:32

2 个答案:

答案 0 :(得分:2)

要解决此问题,您应该重写PHP部分,如下所示:

<?php
    require_once('Includes/dbh.inc.php');

    if(isset($_POST['Title'], $_POST['Text1'])) {
            $Title = mysqli_real_escape_string($conn, $_POST['Title']);
            $content = mysqli_real_escape_string($conn, $_POST['Text1']);
            $sql = "INSERT INTO posts (title, main) VALUES ('$Title', '$content');";
            $result = mysqli_query($conn, $sql);
            if($result !== false) {
                     header("Location: ../Backend.php?Post=success");
                     exit;
            } else {
                     // query failed, do some checks
            }
    }
?>

你必须:

  1. 转义用户的输入以防止SQL注入。
  2. 检查表单是否以POST方式提交
  3. 另外,正如评论中所提到的,HTML充满了错误。您最好使用W3C HTML Validator来检查HTML结构。

答案 1 :(得分:0)

<?php
    include_once 'Includes/dbh.inc.php';

    $Title = $_POST['Title'];
    $content = $_POST['Text1'];
    $sql = "INSERT INTO posts (title, main) VALUES ('$Title', '$content');";
    mysqli_query($conn, $sql);
    header("Location: ../Backend.php?Post=success");
?>

请删除粗体半冒号,您的代码应为

<?php
    include_once 'Includes/dbh.inc.php';

    $Title = $_POST['Title'];
    $content = $_POST['Text1'];
    $sql = "INSERT INTO posts (title, main) VALUES ('$Title', '$content')";
    mysqli_query($conn, $sql);
    header("Location: ../Backend.php?Post=success");
?>

或者您可以使用

<?php
        include_once 'Includes/dbh.inc.php';
        if(isset($_POST['submit'])){
        $Title = $_POST['Title'];
        $content = $_POST['Text1'];
        $sql = "INSERT INTO posts (title, main) VALUES ('$Title', '$content')";
        mysqli_query($conn, $sql);
        header("Location: ../Backend.php?Post=success");
        }else{
            echo "Error";
        }
    ?>