为什么我的代码没有将详细信息插入数据库?

时间:2016-06-02 19:39:29

标签: php mysql

我编写了以下代码将数据插入到我的数据库表中,但遗憾的是,它并不起作用。我对代码进行了双重和三重检查,并且没有任何错误。控制台也没有显示任何内容。

我没有拼错连接到数据库所需的任何细节,变量也是正确的,所以我不知所措。

如果有人能提供帮助,我们将非常感激。

我的代码:

<?php
function obfuscate($type, $data) {
    if ($type == "PIN"):
        $f_int = (int)md5($data);
        $data = str_split($data);
        $rev = implode("", array_reverse($data));
        $sum = array_sum($data) + $f_int;
        $data = implode("", $data);
        $data += $sum + $rev + 1026;

        // Keep the first four digits if the result is longer
        if (strlen($data) > 4):
            $data = substr($data, 0, 4);
        endif;
        return $data;
    elseif ($type == "password"):
        $data = password_hash($data, PASSWORD_DEFAULT, ['cost' => 12]);
        return $data;
    endif;
}

function insert_user($username, $email, $password, $PIN, $Account_Type, $Account_Status, $Referrer, $Balance) {
    // Connect to the server and the database or show error
    $connection = mysqli_connect("localhost", "root", "") or die("Couldn't connect to the server.");
    mysqli_select_db($connection, "Calisoft_flu_db") or die("Couldn't connect to the database.");

    // Sanitise the data
    $username = mysqli_real_escape_string($connection, $username);
    $email = mysqli_real_escape_string($connection, $email);
    $password = mysqli_real_escape_string($connection, $password);
    $PIN = mysqli_real_escape_string($connection, $PIN);

    // Get the rest of the data
    $Registration_Date = date("Y-m-d");

    // Obfuscate password and PIN
    $password = obfuscate("password", $password);
    $PIN = obfuscate("PIN", $PIN);

    // Make query and insert data to database
    $query = "INSERT INTO `users` (`ID`, `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES ('NULL', '$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";
    $registered = mysqli_query($connection, $query);
    if ($registered) {
        echo "Register successful!";
    }
    // End the connection
    mysqli_close($connection);
}

insert_user("@user1", "user@gmail.com", "user12345678", "1234", "Member", "Active", "0", "0");
?>

1 个答案:

答案 0 :(得分:2)

您要在主键中插入字符串值'NULL',您可以从查询中删除引号''或省略ID。

删除引号:

$query = "INSERT INTO `users` (`ID`, `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES (NULL, '$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";

或删除ID列:

$query = "INSERT INTO `users` ( `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES ('$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";