2016-09-10 6 views
1

준비된 문을 스크립트에 구현하고 싶지만 실제로 작동하지 않습니다. 나는 이미 많은 기능을 가지고 있으므로 최대한 조금 변경하고 싶다.php 데이터베이스에 준비된 문을 추가하십시오.

나는 준비된 명령문 기능을 갖는 것이 가장 좋을 것이라고 생각합니까? 그래서 사용자 입력을 받으면 쿼리 대신 해당 함수를 호출 할 수 있습니다.

database.php 클래스는

class MySQLDB { 
    var $connection; // The MySQL database connection 

    /* Class constructor */ 
    function MySQLDB() { 
     global $dbsystem; 
     $this->connection = mysqli_connect (DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die ('Connection Failed (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); 
    } 


    /** 
    * query - Performs the given query on the database and 
    * returns the result, which may be false, true or a 
    * resource identifier. 
    */ 
    function query($query) { 
     return mysqli_query ($this->connection, $query); 
    } 
}; 

/* Create database connection */ 
$database = new MySQLDB(); 

이 내가 다른 클래스에서 데이터베이스를 호출하는 방법입니다.

$q = "UPDATE users SET name = '$name', started = '$time' WHERE id = '$id';"; 
    $result = mysqli_query ($database->connection, $q); 

답변

2

는 귀하의 경우에는이 같은, 조금 청소기 뭔가를 할 것이다 :

<?php 

class MySQLDB{ 

    private function openConnection(){ 

    // If you don't always use same credentials, pass them by params 
    $servername = "localhost"; 
    $username = "username"; 
    $password = "password"; 
    $database = "database"; 

    // Create connection 
    $conn = new mysqli($servername, $username, $password, $database); 

    // Check connection 
    if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
    } 

    // Assign conection object 
    return $conn; 
    } 

    private function closeConnection($conn){ 
    $conn->close(); 
    } 

    function updateUserById($id, $name, $startedTime){ 

    $conn = $this->openConnection(); 

    $sqlQuery = "UPDATE users SET name = ?, started = ? WHERE id = ?"; 

    if ($stmt = $conn->prepare($sqlQuery)) { 

     // Bind parameters 
     $stmt->bind_param("ssi", $name, $startedTime, $id); 

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

     if ($stmt->errno) { 
     die ("Update failed: " . $stmt->error); 
     } 

     $stmt->close(); 
     } 

    $this->closeConnection($conn); 
    } 

} // Class end 

를 지금, 그것을 사용하는, 당신은 단지이해야 할 :

<?php 

$myDBHandler = new MySQLDB; 

$myDBHandler->updateUserById(3, "Mark", 1234); 
+0

내가 좋아하는 것을 좀 더 동적 그래서 내가 이런 식으로 뭔가를 할 것이라고 데이터베이스 클래스 : function query ($ sql, $ statement) { $ conn = $ this-> openConnection(); if ($ stmt = $ conn-> prepare ($ sql)) { $ stmt-> bind_param ($ statement); // 쿼리 실행 $ stmt-> execute(); if ($ stmt-> errno) { die ("Update failed :". $ stmt-> error); } $ stmt-> close(); } $ this-> closeConnection ($ conn); } – Kingfox

관련 문제