<span> 1</span> <?<span>php </span><span> 2</span> <span>$dbh</span> = <span>new</span> PDO('mysql:host=localhost;dbname=access_control', 'root', ''<span>); </span><span> 3</span> <span>$dbh</span>->setAttribute(PDO::ATTR_ERRMODE, PDO::<span>ERRMODE_EXCEPTION); </span><span> 4</span> <span>$dbh</span>-><span>exec</span>('set names utf8'<span>); </span><span> 5</span> <span>/*</span><span>添加</span><span>*/</span> <span> 6</span> <span>//</span><span>$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password"; </span> <span> 7</span> <span>$sql</span> = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)"; <span>$stmt</span> = <span>$dbh</span>->prepare(<span>$sql</span>); <span>$stmt</span>->execute(<span>array</span>(':login'=>'kevin2',':password'=>''<span>)); </span><span> 8</span> <span>echo</span> <span>$dbh</span>-><span>lastinsertid(); </span><span> 9</span> <span>/*</span><span>修改</span><span>*/</span> <span>10</span> <span>$sql</span> = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId"<span>; </span><span>11</span> <span>$stmt</span> = <span>$dbh</span>->prepare(<span>$sql</span><span>); </span><span>12</span> <span>$stmt</span>->execute(<span>array</span>(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'<span>)); </span><span>13</span> <span>echo</span> <span>$stmt</span>-><span>rowCount(); </span><span>14</span> <span>/*</span><span>删除</span><span>*/</span> <span>15</span> <span>$sql</span> = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; <span>//</span><span>kevin% </span> <span>16</span> <span>$stmt</span> = <span>$dbh</span>->prepare(<span>$sql</span><span>); </span><span>17</span> <span>$stmt</span>-><span>execute(); </span><span>18</span> <span>echo</span> <span>$stmt</span>-><span>rowCount(); </span><span>19</span> <span>/*</span><span>查询</span><span>*/</span> <span>20</span> <span>$login</span> = 'kevin%'<span>; </span><span>21</span> <span>$sql</span> = "SELECT * FROM `user` WHERE `login` LIKE :login"<span>; </span><span>22</span> <span>$stmt</span> = <span>$dbh</span>->prepare(<span>$sql</span><span>); </span><span>23</span> <span>$stmt</span>->execute(<span>array</span>(':login'=><span>$login</span><span>)); </span><span>24</span> <span>while</span>(<span>$row</span> = <span>$stmt</span>->fetch(PDO::<span>FETCH_ASSOC)){ </span><span>25</span> <span>print_r</span>(<span>$row</span><span>); </span><span>26</span> <span>} </span><span>27</span> <span>print_r</span>( <span>$stmt</span>->fetchAll(PDO::<span>FETCH_ASSOC)); </span><span>28</span> ?>
1 建立連線
<span>1</span> <?<span>php </span><span>2</span> <span>$dbh</span>=newPDO('mysql:host=localhost;port=3306; dbname=test',<span>$user</span>,<span>$pass</span>,<span>array</span><span>( </span><span>3</span> PDO::ATTR_PERSISTENT=><span>true</span> <span>4</span> <span>)); </span><span>5</span> ?>
持久性連結PDO::ATTR_PERSISTENT=>true
2. 捕捉錯誤
<span> 1</span> <?<span>php </span><span> 2</span> <span>try</span><span>{ </span><span> 3</span> <span>$dbh</span>=newPDO('mysql:host=localhost;dbname=test',<span>$user</span>,<span>$pass</span><span>); </span><span> 4</span> <span> 5</span> <span>$dbh</span>->setAttribute(PDO::ATTR_ERRMODE,PDO::<span>ERRMODE_EXCEPTION); </span><span> 6</span> <span> 7</span> <span>$dbh</span>-><span>exec</span>("SET CHARACTER SET utf8"<span>); </span><span> 8</span> <span>$dbh</span>=<span>null</span>; <span>//</span><span>断开连接</span> <span> 9</span> }<span>catch</span>(PDOException<span>$e</span><span>){ </span><span>10</span> <span>print</span>"Error!:".<span>$e</span>->getMessage()."<br/>"<span>; </span><span>11</span> <span>die</span><span>(); </span><span>12</span> <span>} </span><span>13</span> ?>
3. 事務的
<span> 1</span> <?<span>php </span><span> 2</span> <span>try</span><span>{ </span><span> 3</span> <span>$dbh</span>->setAttribute(PDO::ATTR_ERRMODE,PDO::<span>ERRMODE_EXCEPTION); </span><span> 4</span> <span> 5</span> <span>$dbh</span>->beginTransaction();<span>//</span><span>开启事务</span> <span> 6</span> <span>$dbh</span>-><span>exec</span>("insertintostaff(id,first,last)values(23,'Joe','Bloggs')"<span>); </span><span> 7</span> <span>$dbh</span>-><span>exec</span>("<span>insertintosalarychange(id,amount,changedate) </span><span> 8</span> values(23,50000,NOW())"<span>); </span><span> 9</span> <span>$dbh</span>->commit();<span>//</span><span>提交事务</span> <span>10</span> <span>11</span> }<span>catch</span>(<span>Exception</span><span>$e</span><span>){ </span><span>12</span> <span>$dbh</span>->rollBack();<span>//</span><span>错误回滚</span> <span>13</span> <span>echo</span>"Failed:".<span>$e</span>-><span>getMessage(); </span><span>14</span> <span>} </span><span>15</span> ?>
4. 錯誤處理
a. 靜默模式(預設模式)
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不顯示錯誤
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//顯示警告錯誤,並繼續執行
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//產生致命錯誤,PDOException
<span> 1</span> <?<span>php </span><span> 2</span> <span>try</span><span>{ </span><span> 3</span> <span>$dbh</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$password</span><span>); </span><span> 4</span> <span>$sql</span> = 'Select * from city where CountryCode =:country'<span>; </span><span> 5</span> <span>$dbh</span>->setAttribute(PDO::ATTR_ERRMODE, PDO::<span>ERRMODE_WARNING); </span><span> 6</span> <span>$stmt</span> = <span>$dbh</span>->prepare(<span>$sql</span><span>); </span><span> 7</span> <span>$stmt</span>->bindParam(':country', <span>$country</span>, PDO::<span>PARAM_STR); </span><span> 8</span> <span>$stmt</span>-><span>execute(); </span><span> 9</span> <span>while</span> (<span>$row</span> = <span>$stmt</span>->fetch(PDO::<span>FETCH_ASSOC)) { </span><span>10</span> <span>print</span> <span>$row</span>['Name'] . "/t"<span>; </span><span>11</span> <span> } </span><span>12</span> } <span>//</span><span> if there is a problem we can handle it here </span> <span>13</span> <span>catch</span> (PDOException <span>$e</span><span>) { </span><span>14</span> <span>echo</span> 'PDO Exception Caught. '<span>; </span><span>15</span> <span>echo</span> 'Error with the database: <br />'<span>; </span><span>16</span> <span>echo</span> 'SQL Query: ', <span>$sql</span><span>; </span><span>17</span> <span>echo</span> 'Error: ' . <span>$e</span>-><span>getMessage(); </span><span>18</span> <span>} </span><span>19</span> ?>
1. 使用 query()
<?<span>php </span><span>$dbh</span>->query(<span>$sql</span>); 当<span>$sql</span> 中变量可以用<span>$dbh</span>->quote(<span>$params</span>); <span>//</span><span>转义字符串的数据</span> <span>$sql</span> = 'Select * from city where CountryCode ='.<span>$dbh</span>->quote(<span>$country</span><span>); </span><span>foreach</span> (<span>$dbh</span>->query(<span>$sql</span>) <span>as</span> <span>$row</span><span>) { </span><span>print</span> <span>$row</span>['Name'] . "/t"<span>; </span><span>print</span> <span>$row</span>['CountryCode'] . "/t"<span>; </span><span>print</span> <span>$row</span>['Population'] . "/n"<span>; } </span>?>
2. 使用 prepare, bindParam和 execute [建議用,同時可以用新增、修改、刪除]
<?<span>php </span><span>$dbh</span>->prepare(<span>$sql</span><span>); 产生了个PDOStatement对象 PDOStatement</span>-><span>bindParam() PDOStatement</span>->execute();<span>//</span><span>可以在这里放绑定的相应变量</span> ?>
3. 事物
<?<span>php </span><span>try</span><span> { </span><span>$dbh</span> = <span>new</span> PDO('mysql:host=localhost;dbname=test', 'root', ''<span>); </span><span>$dbh</span>->query('set names utf8;'<span>); </span><span>$dbh</span>->setAttribute(PDO::ATTR_ERRMODE, PDO::<span>ERRMODE_EXCEPTION); </span><span>$dbh</span>-><span>beginTransaction(); </span><span>$dbh</span>-><span>exec</span>("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);"<span>); </span><span>$dbh</span>-><span>exec</span>("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);"<span>); </span><span>$dbh</span>-><span>exec</span>("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);"<span>); </span><span>$dbh</span>-><span>commit(); } </span><span>catch</span> (<span>Exception</span> <span>$e</span><span>) { </span><span>$dbh</span>-><span>rollBack(); </span><span>echo</span> "Failed: " . <span>$e</span>-><span>getMessage(); } </span>?>
PDO常用方法:
PDO::query()主要用於有記錄結果回傳的操作(PDOStatement),特別是select操作。
PDO::exec()主要是針對沒有結果集合回傳的操作。如insert,update等操作。傳回影響行數。
PDO::lastInsertId()傳回上次插入操作最後一條ID,但要注意:如果用insert into tb(col1,col2) values(v1,v2),(v11,v22)..的方式一次插入多條記錄,lastinsertid()傳回的只是第一筆(v1,v2)插入時的ID,而不是最後一筆記錄插入的記錄ID。
PDOStatement::fetch()是用來取得一筆記錄。配合while來遍歷。
PDOStatement::fetchAll()是取得所有記錄集到一個中。
PDOStatement::fetchcolumn([int column_indexnum])用於直接存取列,參數column_indexnum是該列在行中的從0開始索引值,但是,這個方法一次只能取得同一行的一列,只要執行一次,就跳到下一行。因此,用於直接存取某一列時較好用,但要遍歷多列就用不上。
PDOStatement::rowcount()適用於當用query("select ...")方法時,取得記錄的條數。也可以用於預處理。 $stmt->rowcount();
PDOStatement::columncount()適用於當用query("select ...")方法時,取得記錄的列數。
註解:
1、選fetch還是fetchall?
小記錄集時,用fetchall效率高,減少從資料庫檢索次數,但對於大結果集,用fetchall則給系統帶來很大負擔。資料庫要傳送到WEB前端量太大反而效率低。
2、fetch()或fetchall()有幾個參數:
mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]])
array pdostatement::fetchAll(int fetch_style)
_style)
_style)
_style)
_style)
_style)
_style)
_style)_style)
_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style)🎜_style) 🎜fetch_style參數:🎜■$row=$rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH是預設的,可省,傳回關聯和索引。 🎜■$row=$rs->fetchAll(PDO::FETCH_ASSOC); FETCH_ASSOC參數決定回傳的只有關聯數組。 🎜■$row=$rs->fetchAll(PDO::FETCH_NUM); 返回索引數組🎜■$row=$rs->fetchAll(PDO::FETCH_OBJ); 如果fetch()則回傳對象,如果是fetchall() ,傳回由物件組成的二維數組🎜 🎜 以上就介紹了php mysql PDO使用,包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。 🎜 🎜 🎜