首页 > 解决方案 > 从 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");
    }
}

任何帮助将不胜感激!!!

标签: phpmysqlvariablespreg-replace

解决方案


推荐阅读