PHP 鏁版嵁瀵硅薄锛圥HP Data Objects锛孭DO锛夋墿灞曚负PHP璁块棶鏁版嵁搴撳畾涔変簡涓€涓交閲忕骇鐨勪竴鑷存帴鍙c€侾DO鎻愪緵浜嗕竴绉嶉珮鏁堢殑鏂规硶鏉ユ墽琛孲QL鏌ヨ锛屽悓鏃朵繚鎸佷簡瀵瑰悇绉嶆暟鎹簱绯荤粺鐨勫吋瀹规€с€傛湰绡囨枃绔犲皢浠嬬粛濡備綍浣跨敤PDO杩炴帴骞舵搷浣淢ySQL鏁版嵁搴撱€?/p>
涓€銆佸畨瑁呴厤缃甈DO鎵╁睍
鍦ㄥ紑濮嬩箣鍓嶏紝璇风‘淇濇偍鐨凱HP鐜涓凡姝g‘瀹夎骞跺惎鐢ㄤ簡PDO_MYSQL鎵╁睍銆傞€氬父鎯呭喌涓嬶紝鍦╬hp.ini鏂囦欢涓壘鍒癳xtension=pdo_mysql.so锛圠inux绯荤粺锛夋垨extension=php_pdo_mysql.dll锛圵indows绯荤粺锛夛紝鐒跺悗鍘绘帀鍓嶉潰鐨勫垎鍙峰嵆鍙惎鐢ㄨ鎵╁睍銆?/p>
浜屻€佸垱寤篜DO瀹炰緥浠ュ缓绔嬭繛鎺?/h2>
瑕佷娇鐢≒DO涓嶮ySQL杩涜浜や簰锛岄鍏堥渶瑕佸垱寤轰竴涓狿DO瀵硅薄銆備笅闈㈡槸涓€涓畝鍗曠殑绀轰緥浠g爜鐗囨锛?/p>
$dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8mb4';
$username = 'root';
$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爜涓殑DSN锛堟暟鎹簮鍚嶇О锛夊寘鍚簡涓绘満鍦板潃銆佹暟鎹簱鍚嶄互鍙婂瓧绗﹂泦淇℃伅銆傛偍鍙兘闇€瑕佹牴鎹疄闄呮儏鍐佃皟鏁磋繖浜涘弬鏁般€?/p>
涓夈€佹墽琛孲QL璇彞
涓€鏃︽垚鍔熷缓绔嬩簡涓庢暟鎹簱鐨勮繛鎺ワ紝灏卞彲浠ヤ娇鐢≒DO瀵硅薄鎵цSQL璇彞浜嗐€傚浜庣畝鍗曠殑鏌ヨ锛屽彲浠ヤ娇鐢╭uery()鏂规硶锛涜€屽浜庢秹鍙婄敤鎴疯緭鍏ョ殑鏁版嵁锛屽垯寤鸿浣跨敤prepare()鏂规硶閰嶅悎execute()鏂规硶浠ラ槻姝QL娉ㄥ叆鏀诲嚮銆?/p>
1. 鎵ц绠€鍗曟煡璇?/h3>
濡傛灉鍙渶瑕佽繍琛屼竴涓笉浼氭敼鍙樻暟鎹簱鐘舵€佺殑鏌ヨ锛堜緥濡係ELECT锛夛紝鍙互鐩存帴璋冪敤query()鏂规硶锛屽苟閫氳繃fetch()绯诲垪鍑芥暟鑾峰彇缁撴灉銆?/p>
// 鑾峰彇鎵€鏈夌敤鎴?
$stmt = $pdo->query('SELECT FROM users');
while ($row = $stmt->fetch()) {
print_r($row);
}
2. 浣跨敤棰勫鐞嗚鍙?/h3>
褰撻渶瑕佹墽琛屽甫鏈夊弬鏁扮殑鏌ヨ鏃讹紝搴旇鍏堝噯澶囧ソ涓€鏉″寘鍚崰浣嶇鐨凷QL璇彞锛屽啀灏嗗叾浼犻€掔粰prepare()鏂规硶鐢熸垚PDOStatement瀵硅薄锛屾渶鍚庨€氳繃execute()鏂规硶浼犲叆瀹為檯鍊笺€?/p>
// 鎻掑叆鏂扮敤鎴?
$sql = 'INSERT INTO users (name, email) VALUES (:name, :email)';
$stmt = $pdo->prepare($sql);
$stmt->execute([':name' => 'John Doe', ':email' => 'john@example.com']);
鍥涖€佷簨鍔″鐞?/h2>
PDO杩樻敮鎸佷簨鍔$鐞嗗姛鑳斤紝杩欎娇寰楁垜浠彲浠ュ皢澶氫釜SQL鎿嶄綔缁勫悎鎴愪竴涓崟鍏冿紝鍦ㄩ亣鍒伴敊璇椂鑳藉鍥炴粴鎵€鏈夋洿鏀广€傝鍚姩浜嬪姟锛屽彧闇€璋冪敤beginTransaction()鏂规硶锛涙彁浜や簨鍔″垯浣跨敤commit()锛涘鏋滃嚭鐜伴棶棰橈紝鍒欏彲浠ラ€氳繃rollBack()鏉ュ洖婊氥€?/p>
$pdo->beginTransaction();
try {
// 鎵ц涓€绯诲垪鐩稿叧鑱旂殑鎿嶄綔...
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
浜斻€佸叧闂繛鎺?/h2>
铏界劧PHP浼氬湪鑴氭湰缁撴潫鏃惰嚜鍔ㄩ噴鏀捐祫婧愶紝浣嗘樉寮忓湴鏂紑涓庢暟鎹簱鐨勮繛鎺ヤ粛鐒舵槸涓ソ涔犳儻銆傚彲浠ラ€氳繃璁剧疆PDO瀵硅薄涓簄ull鏉ュ疄鐜拌繖涓€鐐广€?/p>
$pdo = null;
鍏€佹€荤粨
閫氳繃PDO鏂瑰紡杩炴帴鍜屾搷浣淢ySQL鏁版嵁搴撲笉浠呭畨鍏ㄥ彲闈狅紝鑰屼笖鍏锋湁鑹ソ鐨勮法骞冲彴鎬у拰鏄撶敤鎬с€傛帉鎻′簡浠ヤ笂鍩烘湰姒傚康鍚庯紝鎮ㄥ彲浠ユ洿鍔犵伒娲诲湴鏋勫缓鍩轰簬PHP鐨勫簲鐢ㄧ▼搴忥紝鍏呭垎鍒╃敤鐜颁唬Web寮€鍙戠殑鏈€浣冲疄璺点€?/p>
本文由阿里云优惠网发布。发布者:编辑员。禁止采集与转载行为,违者必究。出处:https://aliyunyh.com/105306.html
其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。