简体   繁体   中英

if mysql_query with &&

I'm trying to get a successful result if rows in 2 tables were deleted, but my query only executes the first query and then bring back the result as successful, how do I go about this?

if (mysql_query("DELETE FROM ex_test_taken WHERE userid1 = '$userid2' AND testid1 = '$tid2'") && ("DELETE FROM ex_answer WHERE name = '$userid2' AND testname = '$tid2'")) {
echo "Sucesfull";
} else {
echo "Failed";
}

("DELETE FROM ex_answer WHERE name = '$userid2' AND testname = '$tid2'") should be:

mysql_query("DELETE FROM ex_answer WHERE name = '$userid2' AND testname = '$tid2'")

A plain non-empty string always evaluates to true.

Your code is:

if (
    mysql_query("DELETE FROM ex_test_taken WHERE userid1 = '$userid2' AND testid1 = '$tid2'") 
    && ("DELETE FROM ex_answer WHERE name = '$userid2' AND testname = '$tid2'")
   )

So you're basically running one query... try:

if (
    mysql_query("DELETE FROM ex_test_taken WHERE userid1 = '$userid2' AND testid1 = '$tid2'") 
    && 
    mysql_query("DELETE FROM ex_answer WHERE name = '$userid2' AND testname = '$tid2'")
   )

You should note, that mysql_query() returns true if the DELETE statement executed properly. "executed properly" is not the same as "actually deleted any rows". So, unless your query is erroneuous (bad syntax, tables/cols mysql doesn't know), this will always return true .

If you want to know if any data was modified (in your case deleted) use mysql_affected_rows() .

You should use mysql_real_escape_string() on any data you pass to mysql.

<?php

$success = 
  mysql_query('DELETE FROM ex_test_taken WHERE userid1 = "' . mysql_real_escape_string($userid2) . '" AND testid1 = "' . mysql_real_escape_string($tid2) . '"')
  && mysql_affected_rows()
  && mysql_query('DELETE FROM ex_answer WHERE name = "' . mysql_real_escape_string($userid2) . '" AND testname = "' . mysql_real_escape_string($tid2) . '"')
  && mysql_affected_rows();

if ($success) {
  // DELETEd data in both queries
} else {
  // did not DELETE any data in either query
}

You might also want to look into PDO to replace your outdated mysql_* stuff.

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