简体   繁体   中英

Deleting row using PHP Mysql

Trying to delete from table.2 if no row count exist or < than one in table.1. using a variable ($group). I think the problem is after I delete the row in table.1 there's no variable to go by to delete in table.2 so it doesn not delete the row. I don't know if this makes sense. Here's the code.

$q = mysql_query("SELECT `group name` FROM `group` WHERE cid = '$id'") or die(mysql_error());
list($group) = mysql_fetch_row($q);

$n = mysql_query("select count(`group name`) as total from `group` WHERE user_id
= '$_SESSION[user_id]' AND cid = '$id' ");

$r = mysql_fetch_array($n);

if($r['total'] = 0 ) {

mysql_query("DELETE FROM `group log`
             WHERE `group name`='$group'
            ") or die(mysql_error());
}

I've also tried this but it just deletes the row after user deletes all rows:

mysql_query("DELETE FROM `group log` 
 WHERE NOT EXISTS(SELECT NULL
                    FROM `group` g
                   WHERE g.`group name` = `group name`)");
`WHERE g.`group name` = `group name`)

Thats saying

where `group name` = `group name`

Which is always true, I suspect you meant to say

where `group name` = 'group name'

or

where `group name` = $group_name

in the first case you missed a = it should be

if($r['total'] == 0 ) {

If you're just looking to delete records of one table that don't have a corresponding match in a second table, the DELETE method in MySQL supports LEFT JOIN syntax:

DELETE gl.* 
FROM `group log` gl
LEFT JOIN `group` g
ON g.`group name` = gl.`group name`
WHERE g.`group name` IS NULL

Or, if you have a particular group you're looking to delete from the log table:

DELETE gl.* 
FROM `group log` gl
LEFT JOIN `group` g
ON g.`group name` = gl.`group name`
WHERE g.`group name` IS NULL
AND gl.`group name` = '$group'

In addition to the previous answer by exussum, I would exchange

$n = mysql_query("select count(`group name`) as total from `group` WHERE user_id='$_SESSION[user_id]' AND cid = '$id' ");

with

$n = mysql_query("select count(`group name`) as total from `group` WHERE user_id= '{$_SESSION['user_id']}' AND cid = '$id' ");

To avoid an undefined constant error notice, depending on the error settings used:

$_SESSION[user_id] is actually looking for the value of the constant user_id to use as the key in $_SESSION , but defaults to the string 'user_id' (albeit with a warning).

Also, have you checked that the session is started ( session_start() ) and that $_SESSION['user_id'] is set?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM