duanhe1976 2012-08-28 17:57
浏览 124

如何从数据库获取数据时捕获错误或警告

I have a problem. I am trying, but I am not getting the exact solution.

I have code to take something from database.

try {
    require_once('blogic.php');
    $obj  = new blogic();
    $re   = $obj->select("SELECT link FROM eff ORDER BY RAND() LIMIT 1");
    $l    = mysql_fetch_row($re);
    $link = $l[0];
} catch (Exception $e) {
    $link = "http://www.xyz.com/friendsin2013/";
}

The above code is working properly, but if (for whatever reason) any problem comes while getting data from the database, I want the link to be defaulted as given in the catch block.

However it is not working the way I want it to. It works when there is no error, however, when I experience an errorr, $link does not get passed from the catch. I just get the error message instead.

Blogic.php life is like --->> This is a file to get database entry.

<?php

include('s.php');

class blogic {

    function connect() {
        $link = mysql_connect(SERVER, USER, PASSWORD);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
            return false;
        } else {
            return true;
        }
    }

    function select_database() {
        $db = mysql_select_db(DATABASE);
        if (!$db) {
            die('Could not connect: ' . mysql_error());
            return false;
        } else {
            return true;
        }
    }

    function select($str) {
        self::connect();
        self::select_database();

        $res = mysql_query($str);
        return $res;
    }
}
?>

s.php ->>

  • 写回答

2条回答 默认 最新

  • dqf2015 2012-08-28 18:02
    关注

    Write this as a function, then call it; return $link in both the try and catch blocks:

    require_once('blogic.php');
    
    function getLink() {
         try {
            $obj = new blogic();
            $re=$obj->select("SELECT link FROM eff ORDER BY RAND() LIMIT 1");
            $l=mysql_fetch_row($re);
            return $l[0];
        }
        catch(Exception $e) {
            return "http://www.xyz.com/friendsin2013/";
        }
    }
    
    $link = getLink();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答