编辑个人资料 - PDO

时间:2015-04-06 15:02:45

标签: php pdo edit

我正在尝试在我的脚本中包含更改用户个人资料详细信息的页面。我是这样做的,在类user.php我包含了这个:

// Update profile
    public function update($email,$gender,$location) {
        try {
        $stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ? ');
        $stmt->execute(array($email,$gender,$location,$_SESSION['memberID']));
        return $stmt->fetch();
        } catch(PDOException $e) {
            echo '<p class="bg-danger">'.$e->getMessage().'</p>';
        }
    }

虽然,例如,页面account.php,我这样做:

if (isset($_POST['submit'])) {
// new data
$email = $_POST['email'];
$gender = $_POST['gender'];
$location = $_POST['location'];
    $id = $_SESSION['memberID'];

// query
if ($user->update($email,$gender,$location,$id)); {
    redirect('account.php');
}
}

<form action="account.php" method="POST">
Email<br>
<input type="text" name="email" value="<?php echo $_SESSION['email'] ?>" /><br>
Gender<br>
<input type="text" name="gender" value="<?php echo $_SESSION['gender'] ?>" /><br>
Location<br>
<input type="text" name="location" value="<?php echo $_SESSION['location'] ?>" /><br>
<input type="submit" name="submit" value="Save" />
</form>

在PDO中使用连接的方式,但是,我尝试了很多选项,但总是效果不佳。

1 个答案:

答案 0 :(得分:0)

在你班上的方法: 公共功能更新($ email,$ gender,$ location);

它不接受$ id like参数。

所以解决方案可以是: 一个。使用对象的id而不使用$ _SESSION [&#39; memberID&#39;]。

public function update($email,$gender,$location) {
    try {
    $stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ?');
    $stmt->execute(array($email,$gender,$location,$this->id);
    return true;
    } catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    }
    return false;
}

湾在函数中接收id并使用它。如果是这种情况,最好像静态方法一样使用它。

public static function update($email,$gender,$location,$id) {
    try {
    $stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ?');
    $stmt->execute(array($email,$gender,$location,$id);
    return true;
    } catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    }
    return false;
}

所以请根据所使用的策略进行调用。也不要在类模型的方法中回显,只是将其设置为错误消息属性并让调用者执行输出。

希望它有所帮助。