php 如何在选择前添加更新

hgb9j2n6  于 2023-11-16  发布在  PHP
关注(0)|答案(1)|浏览(77)

我如何更新之前已经登录的用户的数据(他们的user_id被记录),然后从数据库中取出他们在这一行$user = $this->pdo->prepare("SELECT * FROM bot_shop_profile WHERE user_id = :user_id"); $user->execute(['user_id' => $chat_id]);完整列表

{
        $user = $this->pdo->prepare("SELECT * FROM bot_shop_profile WHERE user_id = :user_id");
        $user->execute(['user_id' => $chat_id]);
        if ($user->rowCount() == 0) {
            $newUser = $this->pdo->prepare("INSERT INTO bot_shop_profile SET user_id = :user_id, first_name = :first_name, last_name = :last_name, phone = :phone, adress = :adress, action = 'start', username = :username");
            $newUser->execute([
                'user_id' => $chat_id,
                'first_name' => $data['message']['chat']['first_name'],
                'last_name' => $data['message']['chat']['last_name'],
                'username' => $data['message']['chat']['username'],
                'phone' => '',
                'adress' => '',
            ]);
        } else {
            @$this->setActionUser("start", $chat_id);
        }
        
        
    }```

I think it should be an expression with UPDATE

字符串

r7knjye2

r7knjye21#

您可以使用UPDATE语句修改数据库中的现有记录。在您的示例中,如果具有指定user_id的用户已经存在,您希望更新用户的信息。以下是如何修改代码以实现此目的:

$user = $this->pdo->prepare("SELECT * FROM bot_shop_profile WHERE user_id = :user_id");
$user->execute(['user_id' => $chat_id]);

if ($user->rowCount() == 0) {
    // User doesn't exist, insert a new record
    $newUser = $this->pdo->prepare("INSERT INTO bot_shop_profile SET user_id = :user_id, first_name = :first_name, last_name = :last_name, phone = :phone, address = :address, action = 'start', username = :username");
    $newUser->execute([
        'user_id' => $chat_id,
        'first_name' => $data['message']['chat']['first_name'],
        'last_name' => $data['message']['chat']['last_name'],
        'username' => $data['message']['chat']['username'],
        'phone' => '',
        'address' => '',
    ]);
} else {
    // User exists, update the existing record
    $updateUser = $this->pdo->prepare("UPDATE bot_shop_profile SET first_name = :first_name, last_name = :last_name, username = :username WHERE user_id = :user_id");
    $updateUser->execute([
        'user_id' => $chat_id,
        'first_name' => $data['message']['chat']['first_name'],
        'last_name' => $data['message']['chat']['last_name'],
        'username' => $data['message']['chat']['username'],
    ]);

    $this->setActionUser("start", $chat_id);
}

字符串
此代码首先检查具有给定user_id的用户是否存在。如果不存在,则插入新记录。如果用户已经存在,则使用新信息更新现有记录。根据数据库架构调整UPDATE语句中的列名和值。

相关问题