【问题标题】:How do I set a variable `true` when updating the database has been successful?更新数据库成功时如何设置变量“true”?
【发布时间】:2019-06-24 23:23:08
【问题描述】:

在我正在编写的博客上,管理员可以向用户授予“作者”权限。

当 db 表更新成功并且他们的权限设置为“作者”时,管理员将返回所有当前作者的列表。

我想要一条消息(例如“作者已添加。”例如)成功后出现在此站点上。

当然,我认为 db-update 不起作用的可能性很小,但我希望考虑这种情况。

为此,我想在数据库更新时设置一个$newAuthortrue,但尝试使用if 没有成功。

这里是 AdminController 和 UserRepository 中的函数与 db 查询:

//AdminController
public function permissionAuthor()
{
  $id = $_GET['id'];
  $permission = "author";
  $newAuthor = false;
  if($this->userRepository->changePermission($id, $permission)) {
    $newAuthor = true;
  }
  header("Location: authors");
}

//UserRepository
public function changePermission($id, $permission)
{
  $table = $this->getTableName();

  $stmt = $this->pdo->prepare(
    "UPDATE `{$table}` SET `permission` = :permission WHERE `id` = :id");
  $changedPermission = $stmt->execute([
    'id' => $id,
    'permission' => $permission
  ]);
  return $changedPermission;
}

// authors.php / the view
<?php if(isset($newAuthor) && $newAuthor == true):?>
  <p class="error">Author has been added.</p>
<?php endif;?>

我怎样才能实现$newAuthor只有在更新数据库的功能已经成功并且要在视图中显示的消息时才设置为true

编辑

我尝试在UserRepository 中返回$changedPermission。它可能是错误的,因为它没有改变任何东西。

【问题讨论】:

  • 您可以在 permissionAuthor 函数中设置会话变量 $_SESSION['newauthor']=true
  • changePermission() 不会返回任何内容来说明它是否有效。您可以返回 execute() 已工作或检查 rowCount(尽管只有在权限更改时才会设置)。
  • 也不确定$newAuthor 将如何传递到 authors.php 页面。
  • 更新语句不会为 rowCount() 返回正确的值,除非该行实际已更改。因此,如果用户已经拥有作者权限并且您尝试再次将其授予他们,您将遇到问题。这就是为什么我在更新后通过查询数据库中的那一行来验证更新语句是否有效。类似"select count(*) from {$table} where permission = :permission and id = :id"
  • @bassxzero 当用户已经拥有“作者”权限时,不可能再次授予它,我考虑过这种情况

标签: php mysql methods boolean


【解决方案1】:

您可以在更改之前检查权限,看看是否有差异,或者只检查 UPDATE 请求是否成功。

自原型:public PDOStatement::execute ([ array $input_parameters ] ) : bool

您可以通过验证执行函数的返回值来检查请求是否成功,如下所示:

$result = $stmt->execute([
    'id' => $id,
    'permission' => $permission
  ]);

if ($result == FALSE)
    echo 'ERROR';
else
    echo 'ok';

同样将$newAuthor = $this-&gt;userRepository-&gt;changePermission($id, $permission);直接放入permissionAuthor函数中。

但还有一件事,我看不到您在代码中调用permissionAuthor 函数的位置?确定执行了吗?

【讨论】:

  • 这属于帖子的 cmets 部分,而不是作为“答案”。答案应该显示工作。
  • 第二个是我的想法,但我不知道我是如何实现的,我对php很陌生
  • 我无法添加 cmets 我没有足够的声誉.. 哈哈,我将添加解决方案以检查请求是否成功
  • @MathieuGasciolli 没有足够的声誉并不是通过发布评论作为答案来规避评论限制的好理由;事实上,这是失去声誉的好方法
  • 我是用路由做的,permissionAuthor() 方法会在有特定url时执行(点击输入type="submit"时会链接到这个url
猜你喜欢
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2021-08-18
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多