Page 1 of 1

still stuck on joins for blog system :(

Posted: Thu Feb 16, 2012 11:28 pm
by astralkid
I'm having troubles with my blog...
I have 2 tables:
1. posts(id, cat_id, title, contents, date_posted)
2. categories(id, name),

and to delete the category:
<a href="delete_category.php?id=<?php echo $category['id']; ?>">Delete</a>
if i view the categories and try to delete one from my cat_list.php page, it deletes the category from the list, but in my posts table, the cat_id assigned to the deleted category is still there... is there a way to, upon deleting a category, update all cat_id's from all posts and set the value to '1' (Uncategorized) or something like that? Right now if I delete a category, the post still sits there with that cat_id still assigned to it.

Here is my delete function:
function delete($table, $id) {
    if (isset($_GET['id']) && is_numeric($_GET['id'])) {
        $table = mysql_real_escape_string($table);
	$id = (int) $id;

	$query = "SELECT 
			`posts`.`id`, 
			`categories`.`id`,
			FROM `posts`
			    INNER JOIN {`categories`}
			ON `categories`.`id` = `posts`.`id`";

    $query = "DELETE FROM `{$table}` WHERE `id` = '{$id}'";

    if(mysql_query($query)) {
        echo 'Ok';
    } else {
        echo 'Not Ok';
    }
}
};
I've been playing around with joins and what not but I am unsure as what to use to fix this issue. I'm not real sure what the best way to go about doing this would be. I know my sql syntax isn't correct, and I'm probably doing it wrong, but just by playing around with the code, I'm stuck :/

Any and all help is appreciated.

Re: still stuck on joins for blog system :(

Posted: Fri Feb 17, 2012 5:10 pm
by jacek
If you know the category being deleted you can use a simple update
UPDATE `posts` SET `cat_id` = 1 WHERE `cat_id` = DELETED_CAT_ID

Re: still stuck on joins for blog system :(

Posted: Sat Feb 18, 2012 1:40 am
by astralkid
The cat_id is set whenever I click delete from the cat_list page...

i've tried...
WHERE cat_id = $cat_id
WHERE cat_id = $_GET['cat_id']
...etc, but none seem to work.. do I need to do a FOREIGN KEY or a INNER JOIN on c.id to p.cat_id ??

Re: still stuck on joins for blog system :(

Posted: Sun Feb 19, 2012 1:24 am
by jacek
Nope, there is no point in joining here.

you should be able to use what ever variable has the category id in it.

Maybe post your code and explain what didnt work about it ?

Re: still stuck on joins for blog system :(

Posted: Sun Feb 19, 2012 1:26 am
by astralkid
SOLV ED

Re: still stuck on joins for blog system :(

Posted: Sun Feb 19, 2012 10:54 am
by libeco
Why don't you use foreign key constraints? http://dev.mysql.com/doc/refman/5.5/en/ ... aints.html

Re: still stuck on joins for blog system :(

Posted: Sun Feb 19, 2012 12:58 pm
by astralkid
libeco wrote:Why don't you use foreign key constraints? http://dev.mysql.com/doc/refman/5.5/en/ ... aints.html
That's what i did end up using.. I got it working.. can close this please thanks :)