라이브러리

[PHP] Statement::__construct 생성자




PHP에서 Statement::__construct 생성자


PHP의 `Statement` 클래스는 MySQLi 확장에서 사용되는 클래스로, MySQL 쿼리를 실행하는 데 사용됩니다. `__construct` 메서드는 클래스의 생성자로, 객체를 초기화하는 데 사용됩니다.

# Statement::__construct 생성자


`__construct` 생성자는 다음 매개 변수를 받을 수 있습니다.

* `$mysqli`: MySQLi 객체
* `$sql`: 실행할 쿼리

#hostingforum.kr
php

/

 * Statement::__construct

 *

 * @param mysqli $mysqli MySQLi 객체

 * @param string $sql 실행할 쿼리

 */

public function __construct($mysqli, $sql)

{

    // 쿼리 실행

    $this->mysqli = $mysqli;

    $this->sql = $sql;

}



# 예제


#hostingforum.kr
php

// MySQLi 객체 생성

$mysqli = new mysqli("localhost", "username", "password", "database");



// 쿼리 실행

$sql = "SELECT * FROM users";



// Statement 객체 생성

$statement = new Statement($mysqli, $sql);



// 쿼리 실행 결과를 가져옵니다.

$result = $statement->execute();



// 결과를 출력합니다.

while ($row = $result->fetch_assoc()) {

    echo $row["id"] . " " . $row["name"] . "
";

}



# 생성자에서 오류 처리


생성자에서 오류 처리를 하는 방법은 다음과 같습니다.

#hostingforum.kr
php



 * Statement::__construct

 *

 * @param mysqli $mysqli MySQLi 객체

 * @param string $sql 실행할 쿼리

 * @throws Exception 쿼리 실행 오류

 */

public function __construct($mysqli, $sql)

{

    try {

        // 쿼리 실행

        $this->mysqli = $mysqli;

        $this->sql = $sql;

    } catch (Exception $e) {

        // 오류 메시지를 출력합니다.

        echo "쿼리 실행 오류: " . $e->getMessage() . "
";

        throw $e;

    }

}



# 생성자에서 쿼리 파라미터 처리


생성자에서 쿼리 파라미터를 처리하는 방법은 다음과 같습니다.

#hostingforum.kr
php

/**

 * Statement::__construct

 *

 * @param mysqli $mysqli MySQLi 객체

 * @param string $sql 실행할 쿼리

 * @param array $params 쿼리 파라미터

 * @throws Exception 쿼리 실행 오류

 */

public function __construct($mysqli, $sql, $params = [])

{

    try {

        // 쿼리 파라미터를 쿼리 문자열에 삽입합니다.

        $this->sql = str_replace("%s", "'" . implode("','", $params) . "'", $sql);

        // 쿼리 실행

        $this->mysqli = $mysqli;

    } catch (Exception $e) {

        // 오류 메시지를 출력합니다.

        echo "쿼리 실행 오류: " . $e->getMessage() . "
";

        throw $e;

    }

}



# 생성자에서 쿼리 파라미터 처리 예제


#hostingforum.kr
php

// MySQLi 객체 생성

$mysqli = new mysqli("localhost", "username", "password", "database");



// 쿼리 실행

$sql = "SELECT * FROM users WHERE id = %s AND name = %s";



// 쿼리 파라미터

$params = [1, "John"];



// Statement 객체 생성

$statement = new Statement($mysqli, $sql, $params);



// 쿼리 실행 결과를 가져옵니다.

$result = $statement->execute();



// 결과를 출력합니다.

while ($row = $result->fetch_assoc()) {

    echo $row["id"] . " " . $row["name"] . "
";

}



이 예제에서는 쿼리 파라미터를 `Statement` 객체의 생성자에 전달하여 쿼리 문자열에 삽입합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 8,985건 / 126 페이지

검색

게시물 검색