php - 从 PHP 中的 Var 中删除特定字符串
问题描述
我最近建立了一个帐户系统,它显示该帐户发布的帖子,
它在创建帖子时起作用,它将帖子ID添加到account-posts
另一个表中,我的目标是当用户请求删除该帖子时
所以我所做的是如果account-posts
不包含逗号(它在多个帖子之间拆分,当它为空并创建一个帖子时,它只是添加 id 但如果不为空,它将添加一个逗号和空格,然后是 id 所以它看起来像 345、678 一样)它会删除它,但如果它会扫描请求的删除帖子 ID,然后替换“,678”,例如但是当我删除第二个帖子时,我的所有测试都会将整个 var 删除为空
//$_GET['id'] is the post id and $_SESSION['id'] is the account id
$query = "SELECT * FROM `accounts` WHERE id = '".mysqli_real_escape_string($link, $_SESSION['id'])."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
//above is getting the `account-posts`
if (strpos($row['posts'], ',') !== false) {
//the `account-posts` has only one post eg(345 not 345, 678)
if (strpos($row['posts'], $_GET['id'].', ') !== false) {
//if the requested delete is in the middle of `account-posts`
$newposts = preg_replace($_GET['id'].", ", "", $row['posts']);
}
if (strpos($row['posts'], ', '.$_GET['id']) !== false) {
//if the requested delete is at the end of `account-posts`
$newposts = preg_replace(", ".$_GET['id'], "", $row['posts']);
}
//below it updates the `account-posts` to the new removed id
$query = "UPDATE `accounts` SET `posts` = '".mysqli_real_escape_string($link, $newposts)."' WHERE `id` = ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
mysqli_query($link, $query);
//below it deletes the post
$query = "DELETE FROM `listing` WHERE `ID` = '".mysqli_real_escape_string($link, $_GET['id'])."' LIMIT 1";
if ($link->query($query) === TRUE ) {
header("Location: account.php");
}
} else {
$newposts = null;
$query = "UPDATE `accounts` SET `posts` = '".mysqli_real_escape_string($link, $newposts)."' WHERE `id` = ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
mysqli_query($link, $query);
$query = "DELETE FROM `listing` WHERE `ID` = '".mysqli_real_escape_string($link, $_GET['id'])."' LIMIT 1";
if ($link->query($query) === TRUE ) {
header("Location: index.php");
}
}
任何帮助将不胜感激!!!
解决方案
推荐阅读
- jquery - jQuery的点击和函数执行之间的延迟
- javascript - 选择下拉菜单后,动态输入字段无法正确显示
- typescript - 使用列表初始化时,TypeScript List 不会验证元素的类型
- javascript - 有没有办法让猫鼬 findById 函数对已删除和不存在的 id 表现一致?
- node.js - 在 NodeJS 应用程序的服务器端从 MongoDB GridFS 读取文件
- c# - Unity, How to make 两个碰撞器,不碰撞,但仍然可以相互交互
- javascript - 上传文件时突然停止上传
- node.js - 如何在 node.js 服务器的反应中显示图像
- rust - 如何从 jni crate 导入 JavaVM 而不会导致编译错误?
- android - 没有 android:layout_width="match_parent" 的 TextView 选取框