PHP SQL 준비 문에서 코드 반복 방지
대부분의 PHP SQL 준비 문 예에서는 필드 이름이 여러 번 반복됩니다. 변경이 필요한 경우 이러한 반복은 장황하고 오류가 발생하기 쉽습니다. 중복을 최소화하기 위한 몇 가지 솔루션은 다음과 같습니다.
원시 PHP
쿼리에서 필드 절을 생략하고 위치 자리 표시자를 사용하면 자세한 내용을 줄일 수 있습니다. 모든 테이블 열에 Null 또는 기본값이더라도 값이 있는지 확인하세요.
$data = [$taskName, $startDate, $completedDate]; $sql = 'INSERT INTO tasks VALUES(null, ?, ?, ?)'; $db->prepare($sql)->execute($data);
도우미 함수
삽입을 위한 도우미 함수를 생성하면 암호. 이 함수는 필드 이름을 통한 SQL 주입에 주의해야 합니다.
function prepared_insert($conn, $table, $data) { $keys = array_keys($data); $keys = array_map('escape_mysql_identifier', $keys); $fields = implode(",", $keys); $table = escape_mysql_identifier($table); $placeholders = str_repeat('?', count($keys) - 1) . '?'; $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)"; $conn->prepare($sql)->execute(array_values($data)); }
Baby ORM(Object-Relational Mapper)
이 접근 방식은 객체 지향 프로그래밍을 사용하여 자동화합니다. 삽입물 생성. 기본 클래스에는 공통 메서드가 포함되어 있으며 특정 테이블은 하위 클래스로 정의됩니다.
public function create($data): int { $fields = $this->makeFieldList($data); $placeholders = str_repeat('?', count($data) - 1) . '?'; $sql = "INSERT INTO `$this->table` ($fields) VALUES ($placeholders)"; $this->sql($sql, array_values($data)); return $this->db->lastInsertId(); }
class UserGateway extends BasicTableGateway { protected $table = 'gw_users'; protected $fields = ['email', 'password', 'name', 'birthday']; } $data = [ 'email' => '[email protected]', 'password' => 123, 'name' => 'Fooster', ]; $userGateway = new UserGateway($pdo); $id = $userGateway->create($data); echo "Create: $id", PHP_EOL;
이러한 솔루션은 코드를 덜 사용하고 중복된 필드 이름을 방지하여 중복성을 제거합니다.
위 내용은 PHP SQL 준비된 문을 사용할 때 코드 반복을 어떻게 피할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

todropaViewInmysql, "dropviewifexistsview_name;"및 TomodifyAview를 사용하고 "createOrreplaceViewView_NameAsselect ...". "

mysqlViewScaneFeficTicallyINGILIDESIGNPATTORNSLIKEADAPTER, DECIARATOR, FACTORY 및 OBSERVER.1) AdapterPatternAdAptSDataFromDifferentTablesinToAunifiedView.2) Decor

viewsinmysqlarebeneficialforsimplifyingcomplexqueries, envancingsecurity, dataconsistency, andoptimizing promperformance

toeteimpleviewinmysql, usethecreateviewstatement.1) definetheviewwithReateViewview_nameas.2) specifyTesLectStatementToreTrievesiredData.3) usetheViewLikeAtableForqueries.ViewsSimplifyDataAccessAndenHances, ButconSiderFormance

toCreateUserSinmysql, usethecreateuserstatement.1) foralocaluser : createUser'LocalUser '@'localHost'IndifiedBy'SecurePassword '; 2) foremoteUser : createUser'RemoteUser'@'%'reidentifiedBy'StrongPassword ';

mysqlviewshavelimitations : 1) 그들은 upportallsqloperations, datamanipulation throughviewswithjoinsorbqueries를 제한하지 않습니다

적절한 usermanagementInmysqliscrucialforenhancingsecurityandensuringfefficientDatabaseOperation.1) USECREATEUSERTOWDDUSERS,@'localHost'or@'%'.

mysqldoes notimposeahardlimitontriggers, butpracticalfactorsdeteirefectiveuse : 1) ServerConfigurationimpactStriggerManagement; 2) 복잡한 트리거 스케일 스케일 사이드로드; 3) argertableSlowtriggerTriggerPerformance; 4) High ConconcercencyCancaUspriggerContention; 5) m


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경