PHP PDO函数,寻找一些建议

| 我绝不是要任何人重新编写我的代码,而是要寻找可以改进它或实施更好做法的地方。这就是函数的简要工作方式。 函数“ 0”至少接受1个参数,该参数可以是单个ID或ID的数组。它也可以接受要抓取的特定行的值,例如“ 1” 所以我真的只是在寻找改善代码结构/最佳实践/功能逻辑的方法,如下所示:
public function getTaxClass()
{
  $arg = func_get_args();
  $or = \'pa.pid = ?\';
  if(is_array($arg[0]))
  {
    $i = 1; 
    while($i < count($arg[0]))
    {
      $or .= \" OR pa.pid = ?\";
      $i ++;      
    }
  }
  if(count($arg) == 1)
  {
    $pid = $arg[0];
    $row = \"a.*\";
  }
  else if(count($arg > 1))
  {
    $pid = array_shift($arg); 
    $prepared_args = array();
    foreach($arg as $a) {
      $prepared_args[] = \"a.\" . $a;
    }
  $row = implode(\',\', $prepared_args);
  }

  $stmt = _DB::init()->prepare(\"SELECT $row
                                FROM tax_class a
                                INNER JOIN products_to_tax_class pa 
                                ON a.tid = pa.tid
                                WHERE ($or)\"
                              );     
  if(is_array($arg[0]))
  {
    if($stmt->execute($arg[0])) 
      return $stmt->fetch(PDO::FETCH_ASSOC);
  }
  else
  {
    if($stmt->execute(array($pid))) 
      return $stmt->fetch(PDO::FETCH_ASSOC);
  }                 
}
非常感激!     
已邀请:
        我的建议:
public function getTaxClass() {
    $args = func_get_args();

    // columns to select:
    $cols = array();
    for ($i=1; $i<=count($args); $i++) {
        $cols[] = \"a.{$args[$i]}\";
    }
    $cols = count($cols) ? join(\',\', $cols) : \'a.*\';

    // IDs to filter and their placeholders:
    $ids = (array) $args[0];
    $phs = join(\',\', array_fill(0, count($ids), \'?\'));

    $stmt = _DB::init()->prepare(
        \"SELECT {$cols}
        FROM tax_class a
            INNER JOIN products_to_tax_class pa 
            ON a.tid = pa.tid
        WHERE pa.pid IN ({$phs})\"
    );

    if ($stmt->execute($ids)) {
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
附言代码未经测试,可能仍然会发生一些错误:)     

要回复问题请先登录注册