--- id: php-mysql-prepared-statements title: "PHP MySQL Prepared Statements" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["bind_param", "SQL injection prevention", "PHP MySQL 준비된 문장"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.9 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["php", "programming", "w3schools", "mysql", "prepared-statements", "security"] raw_sources: ["https://www.w3schools.com/php/php_mysql_prepared_statements.asp"] applied_in: [] github_commit: "" --- # [[PHP MySQL Prepared Statements]] ## 🎯 한 줄 통찰 (One-line insight) Prepared statements defeat SQL injection specifically because parameter values are transmitted via a SEPARATE protocol from the SQL command itself — the source frames it precisely: "parameter values need not be correctly escaped... if the original statement template is not derived from external input, SQL injection cannot occur," meaning the security guarantee is structural, not just a matter of careful escaping. [S1] ## 🧠 핵심 개념 (Core concepts) - **Two-phase model** — Prepare (send an SQL template with `?` placeholders, server parses/compiles/optimizes without executing) then Execute (bind actual values, run — repeatable with different values). [S1] - **Four advantages** — reduced parsing time (prepared once, executed many times), minimized bandwidth (send only params, not the whole query), security (structural SQL-injection resistance), cleaner code (data separated from SQL). [S1] - **MySQLi `bind_param("types", ...vars)`** — binds variables to `?` placeholders; type string uses `i` (integer), `d` (double), `s` (string), `b` (binary) — one letter per parameter. [S1] - **PDO question-mark style** — `$stmt->execute(['John', 'Doe', ...])` — positional array of values. [S1] - **PDO named-parameter style** — `:firstname` placeholders with `$stmt->bindParam(':firstname', $var, PDO::PARAM_STR)`. [S1] ## 📖 세부 내용 (Details) - MySQLi prepared insert: `$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $firstname, $lastname, $email); $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute();` — reused with different variable values for subsequent inserts. [S1] - PDO positional: `$stmt = $conn->prepare($sql); $stmt->execute(['John', 'Doe', 'john@example.com']);`. [S1] - PDO named: `$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR); ... $stmt->execute();`. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **구조적 보안 보장**: 준비된 문장은 값이 SQL 명령과 별도 프로토콜로 전송되므로, 원본 템플릿이 외부 입력에서 유래하지 않는 한 SQL 인젝션 자체가 발생할 수 없다는 구조적 안전성이 명시됨. [S1] ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — 동일한 prepare()문을 재사용해 서로 다른 값으로 세 번 execute()하는 것이 준비된 문장의 성능 이점을 보여주는 대표 사례다. [S1] ## 💻 코드 패턴 (Code patterns) Reusing one prepared statement with different bound values (PHP/MySQLi): ```php $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); // same statement, new values, no re-parsing ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.90 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[PHP Tutorial]] - **관련 개념:** [[PHP MySQL Insert Multiple]], [[PHP MySQL Select]], [[PHP Form Validation]] - **참조 맥락:** SQL 인젝션 방지의 핵심 기법 — 데이터 조회(Select) 챕터로 이어짐. ## 📚 출처 (Sources) - [S1] W3Schools — PHP MySQL Prepared Statements — https://www.w3schools.com/php/php_mysql_prepared_statements.asp ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "PHP MySQL Prepared Statements" page (Astra wiki-curation, P-Reinforce v3.1 format).