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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊