【问题标题】:What does true false actually do in php真正的假在php中实际上做了什么
【发布时间】:2016-05-13 16:51:50
【问题描述】:

见过很多php函数&很多php脚本,总能找到

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

这个真假有什么作用? false 是否会阻止查询进一步执行?

实际上我有一个登录页面,如果在数据库中找不到用户,我想停止执行,例如:

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

echo "hello";

下面是更多的脚本,只有在结果为 1 时才应该执行

根据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.

所以我在我的本地主机上尝试了一个代码

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

wring 后返回 false 单词 hi 没有被执行 & 当我删除 return false 然后执行 hi 单词

现在我会告诉你我真正想知道的事情

 $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
    }
    }

现在你看到上面我在 else 语句中使用了 if 语句,在 else 中使用了更多 if 语句,这使得我的 php 脚本非常复杂且难以理解

我只是想知道执行如下所示脚本的更好方法是什么

$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 }

由于以下示例,我想停止执行

 $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";

现在总是执行 hi

【问题讨论】:

  • 稍后您可以使用 if(check()) { 然后您设置了 $_POST['example'] 并可以执行需要此变量的其他脚本}。如果您使用 DRY 编程方法,使用这些函数总是更好
  • exitdie() 将停止执行
  • true 和 false 只是值。他们自己什么都不做。与您的第一个示例一样,它返回 true 以指示该功能有效。对于您的第二个示例,它不会像您的评论所说的那样起作用。要停止程序,您需要将 exit();在你的 if 语句中。
  • @BenSwinburne 如果我使用 exit & die 页面将退出并显示空白页

标签: php function


【解决方案1】:

使function停止执行的是控制结构returntruefalseBoolean变量,也分别表示为10


if(function that returns a boolean !=1) 

if 仅在 function that returns a booleantrue (1) 时才会执行


详细了解returnBoolean variables


请注意,由于安全问题,mysql_*PHP7 起已弃用。建议您切换到mysqli_*PDO 扩展。

【讨论】:

  • 如果我使用 exit & die 页面将退出并显示空白页,最好的方法是什么?目前我正在使用 if(mysqli_num_rows($query) !=1) { } else{ echo "hi" }
  • 你想做什么?花点时间好好思考,更新你的问题会尽可能简洁明了。
猜你喜欢
  • 1970-01-01
  • 2013-06-02
  • 2020-11-21
  • 2015-02-26
  • 2017-06-29
  • 2013-06-13
  • 2021-10-25
  • 2011-08-12
  • 1970-01-01
相关资源
最近更新 更多