2014-12-30 3 views
2

mysqli prepared statements로 코드를 프로그래밍하고 있습니다. 나는 초보자이며 코드가 맞는지 전문가에게 물어보고 싶습니다.mysqli 준비 문을 프로그래밍하는 적절한 방법

내 코드는 작동하지만, 나는 전문가가 그것을 할 것입니다 궁금 해서요 :)

function getPaymentMethodName($id) { 
    global $mysqli; 
    if ($stmt = $mysqli->prepare('SELECT name FROM `payment_methods` WHERE id = ?')) { 
     if ($stmt->bind_param('i', $id)) { 
      if ($stmt->execute()) { 
       $stmt->bind_result($name); 
       if ($stmt->fetch()) { 
        $stmt->close(); 
        return $name; 
       } 
      } 
     } 
    } 
    $stmt->close(); 
    return false; 
} 

당신이 내게 조언을 수 있기를 바랍니다.

감사합니다.

+6

난 당신이 [코드 검토 (HTTP를 찾고 생각 : // codereview.stackexchange.com/). –

+2

아마도 전역 변수를 사용하지 말고 아마도 $ mysqli를 인수로 전달할 것입니다. 또는 더 많은 클래스 기반 접근 방식을 사용하십시오. –

+0

Ok Dave, 감사합니다! CodeReview – user3800667

답변

1

PHP 데이터베이스 개체를 살펴보십시오. 쿼리를 mySQL에 바인드하는 데 사용할 수 있습니다. PDO는 mysqli의 대안입니다. 구성 방법, 매개 변수 바인딩 및 쿼리 실행 방법에 대한 구현을 제시합니다. preared 문에

http://php.net/manual/en/book.pdo.php

class Database 
{ 
    /* 
    * Database properties 
    */ 
    private $server = 'localhost'; 
    private $username = 'root'; 
    private $password = 'root'; 
    private $database = 'posts'; 
    public $pdo; 
    public static $instance; 

    /** 
    * Static method used to instantiate singleton 
    * @return [object] Database object 
    */ 
    public static function getInstance() 
    { 
     if (!isset($instance)) { 
      Database::$instance = new Database(); 
     } 
     return Database::$instance; 
    } 

    /** 
    * Connect to DB when class is instantiated 
    */ 
    private function __construct() 
    { 
     $this->connect(); 
    } 

    /** 
    * Connects to the database 
    */ 
    private function connect() 
    { 
     // Assign dsn string 
     $dsn = 'mysql:host=' . $this->server . ';dbname=' . $this->database; 

     try { 
      // Assign connection to $pdo 
      $pdo = new PDO($dsn, $this->username, $this->password); 
     } catch (PDOException $e) { 
      throw new pdoDbException($e); 
     } 

     // $pdo inside the method is added to the classes parameter pdo 
     $this->pdo = $pdo; 

    } 

    /** 
    * Queries database for the argument $sql 
    * @param string $sql 
    * @return Sql Query $statement 
    */ 
    public function query($sql) 
    { 
     // Prepare SQL query 
     $statement = $this->pdo->prepare($sql); 

     // return mysql query array 
     return $statement; 
    } 

    /** 
    * Queries for post of id $id 
    * @param [$id] Post ID 
    * @return [array] 
    */ 
    public function getPost($id) 
    { 
     // Query 
     $stmt = $this->query("SELECT * FROM posts WHERE id=(:id)"); 

     // Binds $id parameter to the PDO 
     $stmt->bindParam(':id', $id); 

     // Execute query 
     $stmt->execute(); 

     // Create an empty array for the posts 
     $posts = array(); 

     while($row = $stmt->fetch()) { 
      // Data is fetched from the database as an array 
      $posts[] = $row; 
     } 

     // Return post in an array 
     return $posts; 
    } 

} 
+0

'connect()'의 메소드에서 mysqli 객체를 반환한다고하지만 실제로는 아무것도 반환하지 않는다. – Yang

+0

구현 아이디어가 매우 좋지 않다. 캡슐화를 깨고 (클래스 속성은 인스턴스화 후에 변경 될 수 있기 때문에), SRP 원칙을 따르고, mysqli와 PDO를 혼합한다 – Yang

+0

그래 네가 맞아. 나는 그 모범을 바꿨다. –

0

예 클래스 mysqli 래퍼 :

<?php 
    /** 
    * New Version 24/10/2014 
    * 
    * mb_internal_encoding('UTF-8'); 
    * mb_regex_encoding('UTF-8'); 
    */ 

    class miDB{ 
    private $result; 
    private $db; 

    // filter_var_array($set,FILTER_SANITIZE_STRING) 
    public function __construct($host,$user,$pass,$bbdd){ 
     $this->db = new mysqli($host,$user,$pass,$bbdd); 
     $this->db->set_charset("utf8"); 
     if ($this->db->connect_errno) { 
      throw new Exception ("Falló la conexión: ".$this->db->connect_error); 
     } 
    } 



    /** 
    * 
    * @param string $sql 
    * @param array $datos 
    * @param object $stmt 
    * 
    * @return 
    */ 
    private function preparaQuery($datos){ 
      $tipos = ''; 
      $conta = 1; 
      foreach($datos as $v){ 
       if (is_int($v)) { 
        $tipos .= 'i'; 
       }elseif(is_bool($v)){ 
        $tipos .= 'i'; 
       }elseif(is_float($v) || is_double($v)){ 
        $tipos .= 'd'; 
       }elseif('blob' == gettype($v)){ 
        $tipos .= 'b'; 
       }else{ 
        $tipos .= 's'; 
       } 
      } 
      $paramsDatos = array_merge(array($tipos), $datos); 
      $params = array(); 
      foreach($paramsDatos as $i=>$v){ 
       $params[$i] = &$paramsDatos[$i]; 
      } 
      return $params; 
    } 






    /** 
    * 
    * @param string $query 
    * @param array $datos 
    * 
    * @return 
    */ 
    public function insert($query,$datos=false){ 
     if(is_array($datos)){ 
      //consulta preparada 
      if($stmt = $this->db->prepare($query)){ 
        call_user_func_array(array($stmt, 'bind_param'), $this->preparaQuery($datos)); 
        if($stmt->execute()){ 
         $result = $stmt->affected_rows; 

        }else{ 
         throw new Exception ("Falló la consulta: ".$this->db->error); 
        } 
        if($result >= 1){ 
         $id = $stmt->insert_id; 
         $stmt->close(); 
         return $id; 
        }else{ 
         $stmt->close(); 
         return false; 
        } 
       }else{ 
        throw new Exception ("Falló : ".$this->db->error.' - '.$stmt->error); 
       } 
     }else{ 
      if($this->db->query($query)){ 
       return $this->db->insert_id; 
      }else{ 
       return false; 
      } 
     } 
    } 

    /** 
    * 
    * @param string $query 
    * @param array $datos 
    * 
    * @return 
    */ 
    public function update($query,$datos=false){ 
     if(is_array($datos)){ 
      //consulta preparada 
      if($stmt = $this->db->prepare($query)){ 
        call_user_func_array(array($stmt, 'bind_param'), $this->preparaQuery($datos)); 
        if($stmt->execute()){ 
         //$result = $stmt->get_result(); 
         $result = $stmt->affected_rows; 
         $stmt->close(); 
        }else{ 
         throw new Exception ("Falló la consulta: ".$this->db->error.' - '.$stmt->error); 
        } 
        if($result >= 1){ 
         return $result; 
        }else{ 
         return false; 
        } 
       }else{ 
        throw new Exception ("Falló : ".$this->db->error); 
       } 
     }else{ 
      $this->db->query($query); 
      return $this->db->affected_rows; 
     } 
    } 

    /** 
    * 
    * @param string $query 
    * @param array $datos 
    * 
    * @return 
    */ 
    public function delete($query,$datos=false){ 
     if(is_array($datos)){ 
      //consulta preparada 
      if($stmt = $this->db->prepare($query)){ 
        call_user_func_array(array($stmt, 'bind_param'), $this->preparaQuery($datos)); 
        if($stmt->execute()){ 
         //$result = $stmt->get_result(); 
         $result = $stmt->affected_rows; 
         $stmt->close(); 
        }else{ 
         throw new Exception ("Falló la consulta: ".$this->db->error.' - '.$stmt->error); 
        } 
        if($result >= 1){ 
         return $result; 
        }else{ 
         return false; 
        } 
       }else{ 
        throw new Exception ("Falló : ".$this->db->error); 
       } 
     }else{ 
      $this->db->query($query); 
      return $this->db->affected_rows; 
     } 
    } 

    /** 
    * 
    * @param string $query 
    * @param array $datos 
    * 
    * @return 
    */ 
    public function select($query,$datos=false){ 
     if(is_array($datos)){ 
      //consulta preparada 
      if($stmt = $this->db->prepare($query)){ 
       call_user_func_array(array($stmt, 'bind_param'), $this->preparaQuery($datos)); 
       if($stmt->execute()){ 
        $result = $stmt->get_result(); 
       }else{ 
        throw new Exception ("Falló la consulta: ".$this->db->error); 
       } 
       $miResult = array(); 
       while ($fila = $result->fetch_assoc()) { 
         $miResult[] = $fila; 
       } 
       $result->free(); 
       $stmt->close(); 
       return $miResult; 
      }else{ 
       throw new Exception ("Falló : ".$this->db->error); 
      }   
     }else{ 
      // consulta sin preparar 
      if ($result = $this->db->query($query)) { 
       $miResult = array(); 
       $result->data_seek(0); 
       while ($fila = $result->fetch_assoc()) { 
        $miResult[] = $fila; 
       } 
       $result->free(); 
       return $miResult; 
      }else{ 
       throw new Exception ("Falló : ".$this->db->error); 
       return false; 
      } 
     } 
    } 



    /** 
    * Get number of affected rows in previous MySQL operation 
    * @return integer 
    */ 
    public function AffectedRows() 
    { 
     return $this->db->affected_rows; 
    } 


    /** 
    * Get number of rows in result 
    * @return integer 
    */ 
    public static function Count() 
    { 
     return $this->db->count; 
    } 


    /** 
    * Get the ID generated in the last query 
    * @return integer 
    */ 
    public static function LastId() 
    { 
     return $this->db->insert_id; 
    } 




} 
?> 

사용 :

$db = new miDB('localhost','root',''); 
$sql = "INSERT INTO myTable (col1, col2, col3) VALUES (?, ?, ?)"; 
$data = array('foo',350, false); 
$db->insert($sql,$data); 
관련 문제