PHP 資料物件 (PDO) 擴充為PHP存取資料庫定義了一個輕量級的一致介面。
<code><span><span><?php</span><span>try</span> { <span>$dsn</span> = <span>"mysql:host=localhost; port=3306; dbname=wsq_hotel; charset=utf-8"</span>; <span>$user</span> = <span>'root'</span>; <span>$psw</span> =<span>'root'</span>; <span>$pdo</span> = <span>new</span> PDO(<span>$dsn</span>,<span>$user</span>,<span>$psw</span>); <span>$sql</span> = <span>'select goods_prices from wsq_goods_info where goods_id=2'</span>; <span>// $sql = "show database";</span><span>$res</span> = <span>$pdo</span>->query(<span>$sql</span>) <span>or</span> var_dump(<span>$pdo</span>->errorInfo()); <span>// var_dump($res);</span><span>$mon</span> = <span>$res</span>->fetch(PDO::FETCH_ASSOC); <span>echo</span><span>$mon</span>[<span>'goods_price'</span>]; } <span>catch</span> (PDOException <span>$e</span>) { <span>echo</span><span>$e</span>->getMessage(); } <span>?></span></span></span></code>
PDO操作事務
<code><span>//开启事务</span><span>beginTransacition()</span><span>//回滚</span><span>rollback()</span><span>//提交</span><span>commit()</span><span>//判断是否处于事务之中</span><span>inTransaction()</span></code>
回傳最後插入行的ID
PDO::lastInsertID()
exec()執行
與query()相比,exec()回傳的是受影響行數
<code><span>$sql</span> = <span>"insert into table values('<span>$val</span>')"</span>; <span>if</span>(<span>false</span>===<span>$pdo</span>-><span>exec</span>(<span>$sql</span>)){ <span>echo</span><span>'执行失败'</span>; }</code>
以上就介紹了PHP之PDO,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。