将数据从表单发送到mysql数据库

时间:2018-12-15 19:05:57

标签: php html database

我输入到注册表中的数据未添加到我的数据库中。代码如下。

第一组php位于html格式的html文件中。我包含的最后一个php代码是registrationUpload.php。

<?php 

include ('registrationUpload.php');
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];

if (!$_POST['submit']) {
    echo "all fields are required";
}
else {
    $sql = "INSERT into accounts (username, password, email, firstname, lastname)
        values ('$username','$password','$email','$firstName','$lastName')";

    if (mysqli_query($conn, $sql) {
        echo "data creation successful";
    }
    else {
        echo "something went wrong";
    }
}

?>


<form action = "registrationUpload.php" method = "POST">
<p>Username</p>
<input type = "text" name = "username" placeholder = "Enter Username">
<p>Password</p>
<input type = "password" name = "password" placeholder = "Enter Password">
<p>Email</p>
<input type = "email" name = "email" placeholder = "Enter Email Address">
<p>First name</p>
<input type = "firstName" name = "firstName" placeholder = "Enter your first name">
<p>Last name</p>
<input type = "lastName" name = "lastName" placeholder = "Enter your last name">
<input type = "submit" name = "submit" value = "Login"><br>

registrationUpload.php

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "5091632u";
$db = "registrations_db";

$conn = new mysqli ($dbhost, $dbuser, $dbpass, $db);

if($conn->connect_error){
    echo "connection failed";
}
else {
    "connection was successful";
}

1 个答案:

答案 0 :(得分:0)

您的问题是拼写错误,缺少)

if (mysqli_query($conn, $sql) {

应为:

if (mysqli_query($conn, $sql)) {

您可能已经使用IDE或体面的文本编辑器或通过检查日志来捕获到这一点。

此外,您需要使用mysqli_error()mysqli_errno()检查错误。

最后,您对SQL injection持开放态度。您需要使用准备好的语句,而不是将变量连接到查询中。仅转义变量是不够的。参见How can I prevent SQL injection in PHP?