简体   繁体   中英

Deleting record from MySQL database

I don't have a lot of experience with MySQL, so there is a very good chance I am missing something very obvious.

I am simply trying to delete a record from a table where the (from_=neighbor and to_=id) OR (from_=id and to_=neighbor) . The problem is the record is never deleted.

  1. The basic database setup (username, password, etc) is correct and is actually in an include file that I have used numerous times.
  2. The name of the table is correct, I triple checked.
  3. The names of the columns in the database are correct, I triple checked.
  4. I know the script is receiving id and neighbor as per the javascript alert tests, and I know that the particular integers received match a record in the database (I triple checked).

This is the code I am using:

 $dbhost = "..."; 
 $dbuser = "...";
 $dbpass = "...";
 $dbname    = "...";

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to mysql");
    mysql_select_db($dbname);

$id = mysql_real_escape_string($_GET['id']);
$neighbor = mysql_real_escape_string($_GET['neighbor']);
$result = mysql_query("DELETE FROM jointable WHERE to_='". $id ."' AND from_='".$neighbor."'") or die(mysql_error()); 
$result = mysql_query("DELETE FROM jointable WHERE from_='". $neighbor ."' AND to_='".$id."'") or die(mysql_error()); 
mysql_close($conn);     

echo "<script type='text/javascript'>
    alert('$id');
    alert('$neighbor');
    <!-- 
    window.location = 'index.php?node=$id';   
    //-->
    </script>";

Build the query into a separate string, then dump it out to see what's really going on:

$sql = <<<EOL
DELETE FROM jointable
WHERE (to_ = '$id') AND (from_ = '$neighbor')
EOL;
$result = mysql_query($sql) or die(mysql_error());

die("<pre>$sql</pre> $result");

Note that I'm running the query only once. Your two queries simply rearrange the WHERE clause, which is pointless. (P and Q) is exactly the same as (Q and P) in this case.

Once you've got the query text, try running it manually yourself in the MySQL monitor, and see what's going on. Turn it into a SELECT query with the same WHERE clause, eg

SELECT *
FROM jointable WHERE (to_ = '$id') AND (from_ = '$neighbor')

and see if that returns anything. Since MySQL isn't spitting out an error on the query, then most likely it's your WHERE clause that's causing it to not find the record you want.

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