php删除mysql数据库中的行

I need to delete some data from mysql. I know a bit of php but get really lost with mysql and really don't want to mess this up... I did make a .sql backup but I need to get this right. That's why i'm posting the question here. I know I will get some crap for not trying myself and posting my code here but to be hosnest.. this is as far as I got before I got stuck:

<?php
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("DATABASE", $con);

$result = mysql_query("SELECT * FROM subscriber");

while($row = mysql_fetch_array($result))
  {
  echo $row['mail'] . " " . $row['snid'];
  echo "<br />";
  }

mysql_close($con);
?>

What i'm really trying to do is this:

  • Locate all rows where status = 0 the in the table called subscription and get the field snid (which is an integer)
  • Then go to the table called subscriber and delete the row with the matching snid (also a field in this tables row)
  • Then go back to subscription and delete the original matched row

Does this make sence?.... I've done my own head in just trying to explain it :(

To do what you've asked, you only need 1 query:

delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;

if subscriber and subscription are liked by the snid key, you should use a foreign key with cascading on delete operations.

http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html

Try something like this :

DELETE a,b FROM subscriber AS a INNER JOIN subscription AS b ON a.snid = b.snid WHERE b.status = 0;

All you need to do is create an if statement in your while loop to check the status, if it's 0 execute the delete on both tables. Here is the code for your while loop:

while($row = mysql_fetch_array($result))
  {
  if($row['status']==0) {
      if(mysql_query("DELETE FROM `subscriber` WHERE `snid`={$row['snid']}") {
        mysql_query("DELETE FROM `subscription` WHERE `snid`={$row['snid']}");
      }
    }
  }

I put an additional if statement on your delete, so that if it does not delete from the subscription table it won't delete from the subscriber table either.

$result = mysql_query("SELECT * FROM subscriber WHERE status=0");

while($row = mysql_fetch_array($result)) {
  mysql_query('DELETE FROM subscription WHERE snid =' . $row['snid']);
  mysql_query('DELETE FROM subscriber WHERE id =' . $row['id']);
}

This should work.

$result = mysql_query("SELECT * FROM subscription WHERE status = 0;");

while($row = mysql_fetch_array($result))
{
  $snid = $row['snid'];
  mysql_query("DELETE FROM subscriber WHERE snid = $snid;");
  mysql_query("DELETE FROM subscription WHERE snid = $snid;");
}