I recently built an account system where it displays posts posted by that account,
it works when a post is created it the adds the post id to the account-posts
in another table and what I aim to do is when the user requests delete that post
So what I have done is if account-posts
does not contain a comma (which is splits between multiple posts, when its empty and a post is created it simply adds the id but if not empty it will add a comma and space then the id so it looks like 345, 678) it deletes it but if it does it scans for the requested delete post id then replaces ", 678" for example however when i remove the second post all of my tests remove the whole var to empty
//$_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");
}
}
Any help is graciously appreciated!!!