php - 使用 PHP 中的用户首选项更新帐户表

标签 php mysql insert-update

我有以下 SQL 数据库:

CREATE TABLE IF NOT EXISTS `accounts` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(50) NOT NULL,
    `password` varchar(255) NOT NULL,
    `email` varchar(100) NOT NULL,
        'experience' enum('Beginner', 'Intermediate', 'Advanced) NULL, Default Beginner,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `accounts` (`id`, `username`, `password`, `email`, 'experience') VALUES (1, 'test', '$2y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', 'test@test.com');

除此之外,我还有一个注册表单,它将使用注册表单将给定的值填充到数据库中。

下面的 HTML 表单将成为更新表单:

<div class="card bg-light">
    <div class="register">
        <h1>Update My Preferences</h1>
        <form action="update_preferences.php" method="post" autocomplete="off">
            <div class="form-group input-group">
                <select name="new_experience" class="form-control">
                    <option selected="">Change Investment Experience</option>
                    <option>Beginner</option>
                    <option>Intermediate</option>
                    <option>Advanced</option>
                </select>
            </div>
            <!-- form-group end.// -->
            <label for="username">
                <i class="fas fa-user"></i>
            </label>
            <input type="text" name="new_username" value="<?=$_SESSION['name']?>" id="username">
            <label for="password">
                <i class="fas fa-lock"></i>
            </label>
            <input type="password" name="new_password" placeholder="" value="" id="password">
            <label for="email">
                <i class="fas fa-envelope"></i>
            </label>
            <input type="email" name="new_email" value="<?=$email?>" id="email">
            <input type="submit" value="Update">
        </form>
    </div>
</div>

我设法为 update_preferences.php 添加了以下代码,但后来我遇到了错误“无法准备语句! fatal error :在第 71 行的/home2/freemark/public_html/update_preferences.php 中调用 bool 值的成员函数 close()”:

<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogindb';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);

if (mysqli_connect_errno()) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['new_experience'], $_POST['new_username'], $_POST['new_password'], $_POST['new_email'])) {
    // Could not get the data that should have been sent.
    die ('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['new_experience']) || empty($_POST['new_username']) || empty($_POST['new_password']) || empty($_POST['new_email'])) {
    // One or more values are empty.
    die ('Please complete the registration form');
}

$new_exp_level=$_POST['new_experience'];
$new_username=$_POST['new_username'];
$new_password=$_POST['new_password'];
$new_email=$_POST['new_email'];

// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {

    if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) {
    die ('Email is not valid!');
    }

    if (preg_match('/[A-Za-z0-9]+/', $_POST['new_username']) == 0) {
    die ('Username is not valid!');
    }

    if (strlen($_POST['new_password']) > 20 || strlen($_POST['new_password']) < 5) {
    die ('Password must be between 5 and 20 characters long!');
    }

    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
    $stmt->bind_param('s', $_POST['new_username']);
    $stmt->execute();
    $stmt->store_result();
    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        // Username already exists
        echo 'Username exists, please choose another!';
    } else {
        // Username doesnt exists, insert new account
    if ($stmt = $con->prepare('UPDATE accounts SET $new_exp_level = ?, $new_username = ?, $new_password = ?, $new_email = ? WHERE id = ?')) {
        // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
        $password = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
        $stmt->bind_param('ssss', $_POST['new_username'], $password, $_POST['new_email'], $_POST['new_experience']);
        $stmt->execute();
        header('Location: login.html');
        exit();
        echo 'You have successfully registered, you can now login!';
    } 

    else {
        // Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
        echo 'Could not prepare statement!';
    }
    }
    $stmt->close();
} else {
    // Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
    echo 'Could not prepare statement!';
}
$con->close();
?>

最佳答案

不确定您坚持的是什么,但查询多个字段更新看起来像这样:

$sql = "UPDATE accounts SET field1 = ?, field2 = ?, field3 = ? WHERE id = ?";
// binding values can be done something like
$stmt->bind_param('ssss', $variable1, $variable2, $variable3, $_SESSION['id']);    

另请阅读 this page关于密码散列和从不存储普通密码。

关于php - 使用 PHP 中的用户首选项更新帐户表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878816/

相关文章:

php - INSERT ON DUPLICATE KEY UPDATE 语句的复杂 mysql 查询错误

java - mysql View 的结果集不匹配

javascript - Vuejs将多选改为简单选择

Mysql 大表与连接

mysql - OFFSET 复杂度 InnoDB

postgresql - 连接字符串而不是仅仅替换它

mysql - 添加或更新 MySQL

php - 根据另一个数组对多维数组进行排序

php - PDO 与 Azure PostgreSQL 建立连接非常慢

php - Memcached奇怪的问题!