Condition Statement - Php Mysqli

2019-06-07 08:12发布

问题:

I am with Confuse with Condition ..

 global $db;

 $sql = " SELECT * FROM TEST";  

 $dbc = mysqli_query($db,$sql)


 if (!$sql || mysqli_num_rows($dbc) == 0)  {
      // rollback - Transaction
 }

 or 

 if (!$sql && mysqli_num_rows($dbc) == 0){
      // rollback - Transaction
 }

should i use (!$sql || mysqli_num_rows($dbc) == 0) OR (!$sql && mysqli_num_rows($dbc) == 0)

AS if $sql is true and mysqli_num_rows($dbc) == 0 ( false ) then too condition is False (roll-backed)

AND if $sql is false and mysqli_num_rows($dbc) == 4 ( true ) then too condition is False (roll-backed)

and if both are false then too roll-backed ..

similarly for :

$resultupdate = " UPDATE TEST SET A="NO" WHERE sid="check" ;

if((!$resultupdate) || (mysqli_affected_rows($db) == 0)) {
  // rollback - Transaction
}

or 

if((!$resultupdate) && (mysqli_affected_rows($db) == 0)){
  // rollback - Transaction
}

回答1:

if (!$dbc || mysqli_num_rows($dbc) == 0)  {
  // rollback - Transaction
}

That's true you're telling php if the query didn't run or it returned 0 rows roll back. meaning in case 1 of these 2 is true you're rolling back

if (!$dbc && mysqli_num_rows($dbc) == 0){
  // rollback - Transaction
}

This, you're telling php that both should be true to roll back. if only one is true what's inside this if won't run. That's not what you want.

$resultupdate = " UPDATE TEST SET A='NO' WHERE sid='check" ;
$update_query=mysqli_query($db, $resultupdate);
if((!$update_query) || (mysqli_affected_rows($update_query) == 0)) {
  // rollback - Transaction
}

for the update, you're testing if the query didn't run, or didn't affect any rows you roll back.



回答2:

Only one condition can work as you want.

if (mysqli_num_rows($dbc) == 0)  {
 // rollback - Transaction
}