我一直在四处浏览,甚至在该站点上,但我在PDO中找不到正确的语法来更新数据,例如用户配置文件的数据。

您可以用html表单给我一个实际的例子吗?
我知道也许我提出了很多要求,但我无法使其成功。

随函附上直到现在为止可以执行的操作,但是无法正常工作。

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

    $stmt = $db->prepare("UPDATE `members` SET `email` = :email, `location` = :location WHERE `memberID` = :id");

    $stmt->bindParam(":email", $email, PDO::PARAM_STR);
    $stmt->bindParam(":location", $location, PDO::PARAM_STR);
    $stmt->bindParam(":id", $_SESSION['memberID'], PDO::PARAM_STR);

    $stmt->execute(array(':email' => $_POST['email'], ':location' => $_POST['location'], ':id' => $id));
}


和,

<form role="form" method="POST" action="<?php $_PHP_SELF ?>">
<div class="form-group">
<label class="control-label">Email</label>
<input type="text" value="<?php echo $_SESSION['email'] ?>" name="email" id="email" class="form-control"/>
</div>
<div class="form-group">
<label class="control-label">Location</label>
<input type="text" value="<?php echo $_SESSION['location'] ?>" name="location" id="location" class="form-control"/>
</div>
<div class="margiv-top-10">
<input type="submit" name="submit" class="btn green" value="Update" >
<a href="profile.html" class="btn default">Annuller </a>
</div>
</form>


我想知道查询同一页面是否安全正确,还是应该创建一个类?您能帮我一个实际的例子吗,因为我已经尝试了一切。

最佳答案

首先,我将解释对您的代码所做的一些更改。

1)除非您使用保留字,否则不需要反引号,因此我将其删除
2)您已经将$id定义为$id = $_SESSION['memberID'];,所以我更改了$stmt->bindParam(":id", $_SESSION['memberID'], PDO::PARAM_STR);
3)如果要绑定参数,则不需要使用数组执行,因此我将$stmt->execute(array(':email' => $_POST['email'], ':location' => $_POST['location'], ':id' => $id));更改为$stmt->execute();
4)您的表单中的action必须回显。

这是结果过程

<?php
if(isset($_POST['submit'])) {

    $email = $_POST['email'];
    $location = $_POST['location'];
    $id = $_SESSION['memberID'];
    $sql = "UPDATE members SET email=:email, location=:location WHERE memberID=:id";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(":email", $email, PDO::PARAM_STR);
    $stmt->bindValue(":location", $location, PDO::PARAM_STR);
    $stmt->bindValue(":id", $id, PDO::PARAM_STR);
    $stmt->execute();
}
?>


这是结果形式(更易于阅读缩进)

<form role="form" method="POST" action="<?php echo $_PHP_SELF ?>">
    <div class="form-group">
        <label class="control-label">Email</label>
        <input type="text" value="<?php echo $_SESSION['email'] ?>" name="email" id="email" class="form-control"/>
    </div>
    <div class="form-group">
        <label class="control-label">Location</label>
        <input type="text" value="<?php echo $_SESSION['location'] ?>" name="location" id="location" class="form-control"/>
    </div>
    <div class="margiv-top-10">
        <input type="submit" name="submit" class="btn green" value="Update" >
        <a href="profile.html" class="btn default">Annuller </a>
    </div>
</form>


编码愉快!

关于php - PDO中的表单以更新数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29586585/

10-11 03:22
查看更多