首页 > 解决方案 > 使用 if else 语句更新或插入数据

问题描述

使用一种形式。试图让用户插入或更新数据库。

试过 var_dump(); 试过error_reporting(E_ALL);

$stmt = $connection->prepare("SELECT * FROM profiles WHERE user=?");
$stmt->bind_param("s", $user);
/* execute prepared statement */
$stmt->execute();

$result = $stmt->get_result();

if (isset($_POST['text']))
{
    if ($result->num_rows)
        $text = ($_POST['text']);
    $birthday = ($_POST['birthday']);
    $gender= ($_GET['gender']);

    $stmt = $connection->prepare("UPDATE profiles SET
    user=?, text=?, birthday=?, gender=?
    WHERE user=?");

    $stmt->bind_param("ssss", $user, $text, $birthday, $gender);

/* execute prepared statement */
    $stmt->execute();
}
//using bound paramaters for profile
else
{
    $stmt = $connection->prepare("INSERT INTO profiles
    (user, text, birthday, gender)
    VALUES (?,?,?,?)");

    $stmt->bind_param("ssss", $user, $text, $birthday, $gender);

/* execute prepared statement */
    $stmt->execute();

/* close statement and connection */
    $stmt->close();
}

确实收到了关于性别的未定义变量(一个单选按钮),但它消失了。数据不插入数据库。有时我会在列中看到 null。

标签: php

解决方案


UPDATE查询有 5 个占位符,但您只在bind_param. 最后你需要另一个$user

    $stmt = $connection->prepare("UPDATE profiles SET
    user=?, text=?, birthday=?, gender=?
    WHERE user=?");

    $stmt->bind_param("sssss", $user, $text, $birthday, $gender, $user);

但是没有必要设置user,因为您只是将其设置为相同的值,因此将其更改为:

    $stmt = $connection->prepare("UPDATE profiles SET
    text=?, birthday=?, gender=?
    WHERE user=?");

    $stmt->bind_param("ssss", $text, $birthday, $gender, $user);

如果该user列是唯一键,您可以将所有代码组合到一个查询中,使用INSERT ... ON DUPLICATE KEY UPDATE.

$stmt = $connection->prepare("
    INSERT INTO profiles (user, text, birthday, gender)
    VALUES (?,?,?,?)
    ON DUPLICATE KEY UPDATE text = VALUES(text), birthday = VALUES(birthday), gender = VALUES(gender)");
$stmt->bind_param("ssss", $user, $texxt, $birthday, $gender);

推荐阅读