Aniket Singh
Aniket Singh

Reputation: 877

What does true false actually do in php

I have seen many php function & many php scripts, I always find

function check() {
    if(isset($_POST['example'])){
        return true;
    } else {
        return false;
    }
}

What does this true & false do? does false stops the query from executing further?

Actually i have a login page where I want to stop the executing if user is not found in database like:

if(mysqli_num_rows($query) !=1) {
    // if result is not 1 then executing must be stop here, hello should not be echo
}

echo "hello";

further down are more script that should be executed only when result is 1

According to http://php.net/manual/en/function.return.php -for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.

So i tried a code at my localhost

$a = 1;
if($a == 0){
echo "Its 0"; }
else{ return; }
echo "hi";

after wring return false the word hi was not executed & when i removed return false then the hi word was executed

Now i will tell you what i really want to know

 $query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
 if(mysqli_num_rows($query3) != 1)
   {
      $er1 = "Username doesn't exist"; 
    }
else{
$query4 ="SELECT * FROM users WHERE email='$email'";
$result1=mysqli_query($connecDB, $query3);
if(mysqli_num_rows($result1) != 1)
   {
      $er1 = "Email doesn't exist"; 
   } else {
    // do this
    }
    }

Now you see above i have used if statement into else statement and more if statement into else which makes my php script very much complicated & very hard to understand

I just want to know what is the better way to execute script like shown below

$query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
     if(mysqli_num_rows($query3) != 1)
       {
          $er1 = "Username doesn't exist"; 
        }
    else{ // stop the execution here & just print this $er1 on the page without exit or die }

i want to stop the execution because of below example

 $a = 1;
if($a == 0){
echo "Its 0 "; }
else{ //if it's not 0 then it means user is not registered do not echo echo hi below }
echo "hi";

Now the hi is always executed

Upvotes: 0

Views: 61

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98921

What makes the function stop executing is the Control Structure return, true or false are Boolean variables, also represented as 1 and 0 respectively.


if(function that returns a boolean !=1) 

The if will only execute if function that returns a boolean is true (1)


Learn more about return and Boolean variables


Please note that mysql_* is now deprecated as of PHP7 because of security issues. It is suggested that you switch to mysqli_* or PDO extensions.

Upvotes: 2

Related Questions