donglunzai4288 2013-09-07 17:37
浏览 40
已采纳

PHP或死亡以及if else条件特性

I have function that performs a mysql_query() and then does some other stuff. I want to be able to perform another mysql_query() only if the first one succeeds.

Here is the function

function myFunction($qtext)
{
  mysql_query($qtext) or die(mysql_error() . "
");
  //do some more stuff
  return true;
}

I'm calling the function and attempting to check if it failed with an if else conditional...

if(!myFunction($query_text))
{
  echo "first query failed";
}
else
{
  mysql_query($query_text1) or die (mysql_error() . "
");
}

This seems to work when the first query passes, but if the first query fails it goes to the or die and returns the mysql_error() text and the echo "first query failed"; line in the conditional is never reached.

Ideally id like to be able to alert the user with the mysql_error text but without or dieing, so I can run more code in the conditional.

Any help with explanations of behavior is greatly appreciated. Thanks.

p.s. I'm a beginner... I'm not sure if Im using the return true; properly in the function

  • 写回答

3条回答 默认 最新

  • dongzhuzhou4504 2013-09-07 17:45
    关注

    You're always returning true in the function - you need to also return false if you're checking it in an if() statement.

    function myFunction($qtext) {
    
        // run the query
        $sql = mysql_query($qtext);
    
        // see if there was a result (or whatever you're checking)
        if(mysql_num_rows($sql) > 0) {
            // do some more stuff
            return true;
        } else {
            return false;
        }
    }
    

    Also, you really should learn mysqli or POD instead of mysql, as mysql is depreciated. I also recommend you don't use die() unless you're testing. Build an error handling function instead - it's actually quite easy and will handle errors gracefully instead of abruptly killing the script and annoying your users. You also don't want to print error messages directly to your browser because it can compromise your site's security. :)

    Just an FYI: I use a database class and run my queries like this. It's fast and clean.

    if($db->get_results("SELECT email FROM users WHERE email='".$db->escape($email)."'")) {
        return true;
    } else{
        return false;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)