空白页面将带有php的HTML表单连接到mysql数据库

时间:2016-06-30 20:46:25

标签: php html mysql database-connection

我按照本教程https://www.youtube.com/watch?v=0BoZc5oUioA创建了从注册表单到数据库的连接。 php代码如下所示:

<?php

$con = mysqli_connect('localhost','root','root');

  if(!$con)
  {
    echo 'Not Connected To Server';
  }

  if(!mysqli_select_db($con,'register'))
  {
    echo 'Database Not Selected'
  }

  $Name = $_POST['username'];
  $Email = $_POST['email'];

  $sql = "INSERT INTO users (Name, Email) VALUES ('$name','$email')";

  if(!mysqli_query($con,$sql))
  {
    echo 'Not Inserted';
  }
  else {
    echo 'inserted';
  }

  header("refresh:2; url=index.htm");

?>

但是,每次我尝试注册并且新数据都应插入数据库中,而不是在浏览器中显示空白页面。该数据库称为“寄存器”,该表称为“用户”。有没有人遇到过这个问题或者知道解决方案?或者知道一个帖子,有人针对这个问题,因为我在谷歌上找不到任何东西。我对任何建议都很有帮助!

编辑:

这是我调用PHP文件的html代码部分:

<form action="insert.php" method="post">

    Name : <input type=text" name="username">
      <br/>
    Email : <input type=text" name="email">
      <br/>
      <input type="submit" value="insert">
</form>

1 个答案:

答案 0 :(得分:2)

mysqli_connect可以输入4个输入:主机,用户名,密码,数据库,或者您仍然可以使用mysqli_select_db。使用mysql预处理语句来停止SQL注入也会更好。像这样:

<?php

$con = mysqli_connect('localhost','root','root', 'database here');

  if(!$con)
  {
    echo 'Not Connected To Server';
  }

  $Name = $_POST['username'];
  $Email = $_POST['email'];

  $sql = "INSERT INTO users (Name, Email) VALUES (?, ?)";

  mysqli_stmt_bind_param($sql, "ss", $Name, $Email); //Bind the name & email vars to the mysql statement
  $query = mysqli_stmt_execute($sql); //Execute the statement
  mysqli_stmt_close($sql); //Close the mysql statement
  mysqli_close($con); //Close the database connection

  if(!$query)
  {
    echo 'Not Inserted';
  }
  else {
    echo 'inserted';
  }

  header("refresh:2; url=index.htm"); //Remove this if you use the jQuery

?>

如果您不想刷新页面,可以使用jQuery / JavaScript向此php文件发送$.ajax请求。这是一个简单的例子:

$(document).ready(function() {
    $(document).on('submit', '#put button name here', function() {
        var name = $('#input name').val();
        var email = $('#input name').val();

        $.ajax({
            type: 'post',
            url: 'scriptname.php',
            data: {
                name:username,
                email:email,
            },
             success: function(res) {
                 //do whatever here after form success
             }
        });
        return false;
      });
    });