如何使用pdo删除数据库中的行($ stmt声明为false)

时间:2019-01-11 10:08:51

标签: php database pdo sql-delete

我正在编写博客以获取php经验。

我希望管理员能够删除帖子,但是当我单击delete-button时,实际上应该使我进入删除帖子的功能,我得到了错误Call to a member function execute() on boolean

这是postsRepository.php的代码,它与数据库和postsAdminController.php中的函数进行交互:

public function deletePost($id)
{
  $table = $this->getTableName();
  $model = $this->getModelName();

  $stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");

  $stmt->execute([
   'id' => $id
  ]);
 }


public function deletePost()
{
  $id = $_GET['id'];

  if ($this->postsRepository->deletePost($id)) {
    header("Location: posts-admin");
    return;
  } else {

  }
}

我已经在$ stmt之前var_dump了$ id,这是正确的,显示的错误表明这是由于$stmt->execute([引起的。

我在var_dump时将$ stmt声明为false,但是为什么?

1 个答案:

答案 0 :(得分:3)

blockUser = async () => { try { const token = await SecureStore.getItemAsync('token'); await axios.post(`${SERVER}/api/v1/users/${this.state.userId}/block`, { headers: { 'Access-token': ACCESS_TOKEN, 'Authorization': `Bearer ${token}`, }, }); this.setState({isBlocked: true, sayHi: this.state.sayHi === 0 ? 0 : 2}); this.showToast(`You\'ve blocked ${this.state.name}`) } catch (error) { console.warn(error) } }; likePhoto = (id) => { SecureStore.getItemAsync('token') .then((token) => axios.post(`${SERVER}/api/v1/images/${id}/like`, { headers: { 'Authorization': `Bearer ${token}`, 'Access-token': ACCESS_TOKEN, }, })) .then(() => this._genImages()) .catch((e) => console.warn(e)) }; <TouchableOpacity key={index} style={[ styles.reportBlockReason, selectReason === item.id ? {backgroundColor: 'rgba(255, 255, 255, 0.5)'} : {} ]} onPress={() => this.setState({selectReason: item.id})} > <Text style={styles.reportBlockReasonText}>{item.title}</Text> </TouchableOpacity> <TouchableOpacity key={index} style={[ styles.reportBlockReason, selectReason === item.id ? {backgroundColor: 'rgba(255, 255, 255, 0.5)'} : {} ]} onPress={() => this.setState({selectReason: item.id})} > <Text style={styles.reportBlockReasonText}>{item.title}</Text> </TouchableOpacity> 的正确语法是

DELETE

删除查询中的DELETE FROM tableName WHERE ...

*为假,因为“如果数据库服务器无法成功准备语句,则PDO :: prepare()返回FALSE或发出PDOException(取决于错误处理)。”

有关更多信息,请检查documentation