鏅畨缃戠粶鎻愪緵浜嗕竴绯诲垪鐨勪簯鏈嶅姟锛屽叾涓寘鎷簡鍙互杩愯PHP搴旂敤绋嬪簭鐨勪富鏈虹幆澧冦€侾DO锛圥HP Data Objects锛夋槸涓€涓交閲忕骇銆佷竴鑷存帴鍙g殑鏁版嵁搴撹闂娊璞″眰銆傞€氳繃PDO锛屽紑鍙戣€呭彲浠ュ湪涓嶅悓鐨勬暟鎹簱涔嬮棿杞绘澗鍒囨崲锛屽悓鏃朵繚鎸佷唬鐮佺殑涓€鑷存€у拰绠€娲佹€с€?/p>
瀹夎鍜岄厤缃甈DO鎵╁睍
澶у鏁扮幇浠HP鐗堟湰榛樿宸茬粡鍖呭惈浜哖DO鏀寔锛屼絾涓轰簡纭繚涓囨棤涓€澶憋紝鍦ㄦ櫙瀹夊钩鍙颁笂浣跨敤PDO涔嬪墠锛岃鍏堢‘璁ゆ偍鐨凱HP鐜涓槸鍚﹀凡瀹夎骞跺惎鐢ㄤ簡鎵€闇€鐨凱DO椹卞姩绋嬪簭銆?/p>
濡傛灉灏氭湭鍚敤锛屾偍鍙互閫氳繃浠ヤ笅姝ラ鏉ユ坊鍔犳垨婵€娲诲畠浠細
- 鐧诲綍鍒版櫙瀹夋帶鍒堕潰鏉裤€?/li>
- 閫夋嫨鈥滅綉绔欑鐞嗏€濅笅鐨勭浉搴旂珯鐐广€?/li>
- 鐐瑰嚮鈥滆缃€濓紝鐒跺悗鎵惧埌涓嶱HP鐩稿叧鐨勯€夐」鍗°€?/li>
- 鏌ョ湅褰撳墠浣跨敤鐨凱HP鐗堟湰锛屽苟妫€鏌ユ槸鍚﹀垪鍑轰簡PDO MySQL绛夋墿灞曘€傚鏋滄病鏈夛紝鍙互閫夋嫨鍏朵粬甯︽湁杩欎簺鎵╁睍鐨凱HP鐗堟湰鎴栬€呮墜鍔ㄦ坊鍔犳墿灞曘€?/li>
鍒涘缓PDO杩炴帴
涓€鏃︾‘璁DO鎵╁睍鍙敤锛屾帴涓嬫潵灏卞彲浠ュ紑濮嬬紪鍐橮HP浠g爜鏉ヨ繛鎺ユ暟鎹簱浜嗐€備笅闈㈡槸涓€涓畝鍗曠殑渚嬪瓙锛屽畠婕旂ず浜嗗浣曞缓绔嬩竴涓狿DO杩炴帴:
$dsn = 'mysql:host=your_host;dbname=your_database;charset=utf8mb4';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dsn, $username, $password);
// 璁剧疆閿欒妯″紡涓哄紓甯?
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
璇峰皢涓婅堪浠g爜涓殑`your_host`銆乣your_database`銆乣your_username`鍜宍your_password`鏇挎崲涓烘偍瀹為檯鐨勬暟鎹簱淇℃伅銆?/p>
鎵ц鏌ヨ
浣跨敤PDO鎵цSQL鏌ヨ闈炲父鐩磋銆傛棤璁烘槸璇诲彇鏁版嵁杩樻槸淇敼鏁版嵁锛岄兘鍙互閫氳繃棰勫鐞嗚鍙?prepared statements)鏉ユ彁楂樺畨鍏ㄦ€у拰鏁堢巼銆傝繖閲屾湁涓€浜涘熀鏈殑鎿嶄綔绀轰緥锛?/p>
SELECT鏌ヨ
褰撻渶瑕佷粠鏁版嵁搴撲腑妫€绱㈡暟鎹椂锛屽彲浠ュ儚杩欐牱浣跨敤`prepare()`鏂规硶锛?/p>
$stmt = $pdo->prepare("SELECT FROM users WHERE status = :status");
$stmt->execute(['status' => 1]);
while ($row = $stmt->fetch()) {
print_r($row);
}
INSERT/UPDATE/DELETE鎿嶄綔
瀵逛簬鎻掑叆銆佹洿鏂版垨鍒犻櫎璁板綍锛屽悓鏍峰簲璇ヤ娇鐢ㄩ澶勭悊璇彞浠ラ槻姝QL娉ㄥ叆鏀诲嚮锛?/p>
// 鎻掑叆鏂扮敤鎴?
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => 'John Doe', 'email' => 'john@example.com']);
// 鏇存柊鐢ㄦ埛淇℃伅
$stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
$stmt->execute(['name' => 'Jane Doe', 'id' => 1]);
// 鍒犻櫎鐢ㄦ埛
$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->execute(['id' => 2]);
浜嬪姟澶勭悊
PDO杩樻彁渚涗簡瀵逛簨鍔$殑鏀寔锛岃繖瀵逛簬淇濊瘉涓€缁勭浉鍏虫搷浣滆涔堝叏閮ㄦ垚鍔熷畬鎴愶紝瑕佷箞瀹屽叏鍥炴粴鑷冲叧閲嶈銆備緥濡傦紝褰撲綘鎯冲湪涓€涓簨鍔′腑鎵ц澶氫釜鎻掑叆鎿嶄綔鏃讹紝鍙互杩欐牱鍋氾細
$pdo->beginTransaction();
try {
// 鎵ц涓€绯诲垪鎿嶄綔...
$pdo->exec("INSERT INTO table1 ...");
$pdo->exec("INSERT INTO table2 ...");
// 濡傛灉鎵€鏈夋搷浣滈兘鎴愬姛锛屽垯鎻愪氦浜嬪姟
$pdo->commit();
} catch (Exception $e) {
// 濡傛灉鍙戠敓浠讳綍閿欒锛屽垯鍥炴粴浜嬪姟
$pdo->rollBack();
throw $e;
}
閫氳繃浠ヤ笂浠嬬粛锛岀浉淇¤鑰呭凡缁忔帉鎻′簡濡備綍鍦ㄦ櫙瀹塒HP骞冲彴涓婂埄鐢≒DO鏉ヨ繘琛岄珮鏁堢殑鏁版嵁搴撴搷浣溿€侾DO涓嶄粎绠€鍖栦簡璺ㄤ笉鍚岀被鍨嬬殑鏁版嵁搴撳伐浣滅殑娴佺▼锛岃€屼笖杩樺寮轰簡搴旂敤绋嬪簭鐨勫畨鍏ㄦ€у拰鎬ц兘銆傚笇鏈涜繖绡囨枃绔犺兘澶熷府鍔╂偍鏇村ソ鍦扮悊瑙e拰搴旂敤PDO鎶€鏈€?/p>
本文由阿里云优惠网发布。发布者:编辑员。禁止采集与转载行为,违者必究。出处:https://aliyunyh.com/148265.html
其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。