更好的代码建议?

时间:2012-09-10 11:00:55

标签: php oop

有人可以让我的代码更好/更容易吗?我认为现在编码很糟糕。

我想调用INSERT MYSQLI命令函数如下:

DatabaseHandler::__i('TABLENAME', array('username' => 'foobar', 'password' => 'world'));

我现在正在使用它,但它不起作用,我认为有更好的机会。

public function __i($table, $arr) { $c=$this->connection;
   foreach ( $arr as $name => $val):
      $param1.=$name . ",";
      $param2.="?,";
   endforeach;

   $PARAM1 = substr_replace($param1, '', -1);
   $PARAM2 = substr_replace($param2, '', -1);

   $query = 'INSERT INTO '.$table.' ('.$PARAM1.') VALUES ('.$PARAM2.')';

   foreach ( $arr as $name => $val):
    if ( is_int($val)) :
         $param = 'i';
      endif;

      if ( is_string($val)) :
         $param = 's';
      endif;

      if ( is_double($val)) :
         $param = 'd';
      endif;
      $binds.=$param;
      $values.="'".$arr[$name]."',";

    endforeach;

    $values = substr_replace($values, '', -1);

   if ( $s = $c->prepare($query)):

      $args = $binds + $values;
      call_user_func_array(array($s, 'bind_param'), array($binds, $values));
      $s->execute();
      $s->close();
   endif;

}

1 个答案:

答案 0 :(得分:0)

很难说什么不起作用,你应该发现自己,但我会这样写:

<?php

/**
 * Prepares and executes an 'INSERT' query
 * 
 * @param string $table
 * @param array $arr
 */
public function __i( $table, $arr ) {

    $c = $this -> connection;

    foreach ( $arr as $name => $val ) {
        $param1 .= $name . ",";
        $param2 .= "?,";
    }

    $PARAM1 = substr_replace( $param1, '', -1 );
    $PARAM2 = substr_replace( $param2, '', -1 );

    $query = 'INSERT INTO ' . $table . ' (' . $PARAM1 . ') VALUES (' . $PARAM2 . ')';

    foreach ( $arr as $name => $val ) {

        switch ( gettype( $val ) ) {
            case 'integer': $param = 'i'; break;
            case 'string': $param = 's'; break;
            case 'double': $param = 'd'; break;
        }

        $binds .= $param;
        $values .= "'" . $arr[$name] . "',";

    }

    $values = substr_replace( $values, '', -1 );

    if ( $s = $c -> prepare( $query ) ) {

        $args = $binds + $values;
        call_user_func_array( array( $s, 'bind_param' ), array( $binds, $values ) );
        $s -> execute();
        $s -> close();
    }

}

?>