简体   繁体   English

减少MySQL查询的If语句

[英]Reduce If Statements For MySQL Query

I know there are duplicates of this question, and the answer was to refactor the code. 我知道这个问题有重复之处,答案是重构代码。

However I'm not sure where to begin with this particular function. 但是,我不确定从哪里开始使用此特定功能。

I'm practising my OOP API skills in PHP5 and decided to write my own little Database API. 我正在用PHP5练习OOP API技能,因此决定编写自己的小型Database API。

I have a function with 4 nested if statements, Im not even sure if 4 nested if's are a lot. 我有一个带有4个嵌套的if语句的函数,我什至不确定4个嵌套的if语句是否很多。

But this piece of code just seems messy to me and was wondering if anybody could provide any tips of how to optimise, reduce if's etc. 但是这段代码对我来说似乎很杂乱,并且想知道是否有人可以提供有关如何优化,减少if等的任何提示。

How would this kind of function be written in a real-world scenario? 在现实世界中如何编写这种功能?

My Code Follows: 我的代码如下:

public function custom_query( $sql_query_string, $single_column = false){

    $link = $this->_Link_ID;

    // IF LINK IS VALID RESOURCE
    if ( is_resource( $link ) ) {

        $query_resource = mysql_query( $sql_query_string, $link );

        // IF QUERY WAS VALID
        if ( is_resource( $query_resource ) ) {

            $this->_Query_ID = $query_resource;

            $row_count = mysql_num_rows( $query_resource );

            // IF $ROW_COUNT IS A NUMBER, VALID ROWS WERE FOUND
            if ( is_numeric( $row_count ) ) {

                if ( $single_column ){

                    $result_set = mysql_fetch_assoc( $query_resource );
                    return $result_set;
                }

                else {

                    $result_set = array();
                    for ( $row = 0; $row < $row_count; $row++ ) {
                        $result_set[$row] = mysql_fetch_assoc( $query_resource );
                    }
                    return ( object ) array ( 'row_count' => $row_count, 'result_set' => $result_set );
                }
            }

            else {
                die( "Failed To Retrieve Row Count Query: $sql_query_string MySQL Error: " . mysql_error( $link ) );
            }
        }
        else {
            die( "Invalid Query : $query_string. MySql : " . mysql_error( $link ) );
        }
    }
    else {
        die( "Query attempted without valid link resource.  Query : $query_string" );
    }
}

Thanks, 谢谢,

Alex 亚历克斯

Since you don't have a problem with die -ing in the middle of the function, you can save some intendation space by simply negating the if s: 由于您对函数中间的die -ing没问题,因此可以通过简单地将if s取反来节省一些意向空间:

public function custom_query( $sql_query_string, $single_column = false){

    $link = $this->_Link_ID;

    // IF LINK IS VALID RESOURCE
    if ( !is_resource( $link ) ) die( "Query attempted without valid link resource.  Query : $query_string" );

    $query_resource = mysql_query( $sql_query_string, $link );

    // IF QUERY WAS VALID
    if ( !is_resource( $query_resource ) ) die( "Invalid Query : $query_string. MySql : " . mysql_error( $link ) );

    $this->_Query_ID = $query_resource;

    $row_count = mysql_num_rows( $query_resource );

    // IF $ROW_COUNT IS A NUMBER, VALID ROWS WERE FOUND
    if ( !is_numeric( $row_count ) ) die( "Failed To Retrieve Row Count Query: $sql_query_string MySQL Error: " . mysql_error( $link ) );

    if ( $single_column ) {

        $result_set = mysql_fetch_assoc( $query_resource );
        return $result_set;
    }

    else {

        $result_set = array();
        for ( $row = 0; $row < $row_count; $row++ ) {
            $result_set[$row] = mysql_fetch_assoc( $query_resource );
        }
        return ( object ) array ( 'row_count' => $row_count, 'result_set' => $result_set );
    }
}

If you decide to stop using die() in your function you can rewrite your code to form: 如果决定停止在函数中使用die() ,则可以将代码重写为以下形式:

class Yours {
  protected $errno = 0;
  protected $error = '';

  public function custom_query( $sql_query_string, $single_column = false){

    $link = $this->_Link_ID;

    // IF LINK IS VALID RESOURCE
    if ( !is_resource( $link ) ){
       $this->error = "Query attempted without valid link resource.  Query : $query_string";
       $this->errno = -1;
       return null;
    }
    ...
  }

}

Or you can use exceptions; 或者您可以使用异常;

  public function custom_query( $sql_query_string, $single_column = false){

    $link = $this->_Link_ID;

    // IF LINK IS VALID RESOURCE
    if ( !is_resource( $link ) ){
       throw new Exception( "Query attempted without valid link resource.  Query : $query_string", -1);
    }
    ...
  }

I personally would go for exceptions... But I guess there are people that disagree with me and I'd like to read their arguments. 我个人会寻求例外...但是我想有些人不同意我,我想阅读他们的论点。

EDIT Exception example. EDIT异常示例。 We'll extend php Extension class : 我们将扩展php Extension类

class DbException {
  protected $sql;

  public __construct( $message = "", $code = 0, $sql = '', $previous = NULL){
    parent::__construct( $message, $code, $previous);
    $this->sql = $sql;
  }

  public function getSql(){
    return $this->sql;
  }
}

// In model:
throw new DbException( "Query attempted without valid link resource.", -1, $query);

// In main application:
try {
  ob_start();
  // run whole application
} catch( DbException &e){
  ob_clean(); // Suppress all output so far

  echo "<html><body><div class="error">" . htmlspecialchars( $e->getMessage()) . "</div>";
  if( NOT_IN_PRODUCTION){
    echo "<div class='sql'>" . htmlspecialchars( $e->getSql()) . "</div>";
  }
  echo "</body></html>";
}

Exceptions: 例外情况:

  • provide backtrace (for easy debugging) 提供回溯(便于调试)
  • can be caught by type (and therefore you can handle them in appropriate place or let them propagate to main application) 可以按类型捕获(因此您可以在适当的位置处理它们,或让它们传播到主应用程序)
  • can contain additional info for better debugging 可以包含其他信息以进行更好的调试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM