为什么INSERT在mysql表中的每个查询下面添加额外的空行?

时间:2018-01-29 20:01:38

标签: php mysqli

我的代码:


    $conn = mysqli_connect($servername, $username, $password, $database);

    $n = mysqli_real_escape_string($conn, $_REQUEST['n']);
    $m = mysqli_real_escape_string($conn, $_REQUEST['m']);

    $sql = "INSERT INTO wishform (n,m) VALUES ('$n','$m');";

    if(mysqli_query($conn, $sql)) {
         echo "Your ID is created successfully!";
    } else {
         echo "Error!";
    }

    mysqli_close($conn);
    

在表格中:


    308 Name1   Messege1
    309     
    310 Name2   Messege2
    311     
    312 Name3   Messege3
    313

1 个答案:

答案 0 :(得分:1)

我认为问题是,您没有检查数据是否已提交。 比如说,您已经在PHP文件中原样编写了这段代码,而没有检查用户是否提交了任何数据,并且$_REQUEST['n']$_REQUEST['m']不为空!

因此,如果您没有检查数据是否已提交,那么每次执行页面时您可能正在运行该段代码,并将空数据插入数据库!

这是一个让你入门的简单想法:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    //-- get the data from $_POST array (since we are expecting the data submitted via POST method, otherwise use $_GET array)
    //-- we are trimming any extra spaces
    $n = trim( $_POST['n'] );
    $m = trim( $_POST['m'] );

    if( ! empty( $n ) AND ! empty( $m ) )
    {
        $conn = mysqli_connect($servername, $username, $password, $database);

        $n = mysqli_real_escape_string($conn, $n);
        $m = mysqli_real_escape_string($conn, $m);

        $sql = "INSERT INTO wishform (n,m) VALUES ('$n','$m');";

        if(mysqli_query($conn, $sql)) {
             echo "Your ID is created successfully!";
        } else {
             echo "Error!";
        }

        mysqli_close($conn);
    }
    else
        echo 'No data submitted!';

}

希望它有所帮助!