
TableInsert::__construct 메서드는 TableInsert 클래스를 초기화하는 역할을 합니다. 이 메서드는 데이터베이스 연결 정보를 설정하는 데 사용됩니다.
TableInsert::__construct 메서드의 파라미터는 다음과 같습니다.
- $db: 데이터베이스 연결 객체
- $table: 삽입할 테이블 이름
- $fields: 삽입할 필드 이름의 배열
- $values: 삽입할 필드 값의 배열
TableInsert 클래스를 사용하여 데이터베이스에 테이블을 삽입하는 예시 코드는 다음과 같습니다.
#hostingforum.kr
php
class TableInsert {
private $db;
private $table;
private $fields;
private $values;
public function __construct($db, $table, $fields, $values) {
$this->db = $db;
$this->table = $table;
$this->fields = $fields;
$this->values = $values;
}
public function insert() {
$sql = "INSERT INTO $this->table (" . implode(", ", $this->fields) . ") VALUES (" . implode(", ", $this->values) . ")";
$this->db->query($sql);
}
}
// 데이터베이스 연결 객체를 생성합니다.
$db = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
// 테이블 이름, 필드 이름, 필드 값의 배열을 생성합니다.
$table = "mytable";
$fields = array("id", "name", "email");
$values = array(1, "John Doe", "john@example.com");
// TableInsert 클래스를 생성합니다.
$tableInsert = new TableInsert($db, $table, $fields, $values);
// insert 메서드를 호출합니다.
$tableInsert->insert();
이 예시 코드에서는 TableInsert 클래스를 사용하여 "mytable" 테이블에 "id", "name", "email" 필드의 값을 삽입합니다.
2025-07-25 07:07