php mysql PDO使用

來源:互聯網
上載者:User

$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', '');<br />$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br />$dbh->exec('set names utf8');<br />/*添加*/<br />//$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password";<br />$sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)";<br />$stmt = $dbh->prepare($sql);<br />$stmt->execute(array(':login'=>'kevin2',':password'=>''));<br />echo $dbh->lastinsertid();<br />/*修改*/<br />$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";<br />$stmt = $dbh->prepare($sql);<br />$stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'));<br />echo $stmt->rowCount();<br />/*刪除*/<br />$sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin%<br />$stmt = $dbh->prepare($sql);<br />$stmt->execute();<br />echo $stmt->rowCount();<br />/*查詢*/<br />$login = 'kevin%';<br />$sql = "SELECT * FROM `user` WHERE `login` LIKE :login";<br />$stmt = $dbh->prepare($sql);<br />$stmt->execute(array(':login'=>$login));<br />while($row = $stmt->fetch(PDO::FETCH_ASSOC)){<br />print_r($row);<br />}<br />print_r( $stmt->fetchAll(PDO::FETCH_ASSOC) ); 

mysql常用: http://blog.csdn.net/yjj1s/archive/2011/05/23/6440345.aspx

1 建立串連

$dbh = new PDO('mysql:host=localhost; port=3306; dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

持久性連結 PDO::ATTR_PERSISTENT => true

2. 捕捉錯誤

try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

    $dbh->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_EXCEPTION);

    $dbh->exec("SET CHARACTER SET utf8");
    $dbh = null;  //中斷連線
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

3. 事務的

try {  
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh->beginTransaction();//開啟事務
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate) 
      values (23, 50000, NOW())");
  $dbh->commit();//提交事務
  
} catch (Exception $e) {
  $dbh->rollBack();//錯誤復原
  echo "Failed: " . $e->getMessage();
}

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

try<br />{<br /> $dbh = new PDO($dsn, $user, $password);<br /> $sql = 'Select * from city where CountryCode =:country';<br /> $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);<br /> $stmt = $dbh->prepare($sql);<br /> $stmt->bindParam(':country', $country, PDO::PARAM_STR);<br /> $stmt->execute();<br /> while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {<br /> print $row['Name'] . "/t";<br /> }<br />}<br />// if there is a problem we can handle it here<br />catch (PDOException $e)<br />{<br /> echo 'PDO Exception Caught. ';<br /> echo 'Error with the database: <br />';<br /> echo 'SQL Query: ', $sql;<br /> echo 'Error: ' . $e->getMessage();<br />} 

==========================

1. 使用 query()

    $dbh->query($sql); 當$sql 中變數可以用  $dbh->quote($params); //逸出字元串的資料

$sql = 'Select * from city where CountryCode ='.$dbh->quote($country);<br /> foreach ($dbh->query($sql) as $row)<br /> {<br /> print $row['Name'] . "/t";<br /> print $row['CountryCode'] . "/t";<br /> print $row['Population'] . "/n";<br /> } 

 

2. 使用 prepare, bindParamexecute [建議用,同時可以用添加、修改、刪除]

    $dbh->prepare($sql); 產生了個 PDOStatement 對象

    PDOStatement->bindParam()

    PDOStatement->execute();//可以在這裡放綁定的相應變數

3. 事物

<?php<br />try {<br />$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '');<br />$dbh->query('set names utf8;');<br />$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br />$dbh->beginTransaction();<br />$dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);");<br />$dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);");<br />$dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);");<br />$dbh->commit();<br />} catch (Exception $e) {<br />$dbh->rollBack();<br />echo "Failed: " . $e->getMessage();<br />}<br />?> 

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)

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(),返回由對象組成的二維數組,

pdo mysql dsn(Data Source Name) http://www.php.net/manual/zh/ref.pdo-mysql.connection.php

 

參考: http://hi.baidu.com/traindiy/blog/item/050f3087a544e621c75cc378.html

http://www.php.net/manual/zh/book.pdo.php 

  • PDO — The PDO class

    • PDO::beginTransaction — Initiates a transaction
    • PDO::commit — Commits a transaction
    • PDO::__construct — Creates a PDO instance representing a connection to a database
    • PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
    • PDO::exec — Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute — Retrieve a database connection attribute
    • PDO::getAvailableDrivers — Return an array of available PDO drivers
    • PDO::inTransaction — Checks if inside a transaction
    • PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
    • PDO::prepare — Prepares a statement for execution and returns a statement object
    • PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote — Quotes a string for use in a query.
    • PDO::rollBack — Rolls back a transaction
    • PDO::setAttribute — Set an attribute
  • PDOStatement — The PDOStatement class
    • PDOStatement->bindColumn — Bind a column to a PHP variable
    • PDOStatement->bindParam — Binds a parameter to the specified variable name
    • PDOStatement->bindValue — Binds a value to a parameter
    • PDOStatement->closeCursor — Closes the cursor, enabling the statement to be executed again.
    • PDOStatement->columnCount — Returns the number of columns in the result set
    • PDOStatement->debugDumpParams — Dump an SQL prepared command
    • PDOStatement->errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement->errorInfo — Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement->execute — Executes a prepared statement
    • PDOStatement->fetch — Fetches the next row from a result set
    • PDOStatement->fetchAll — Returns an array containing all of the result set rows
    • PDOStatement->fetchColumn — Returns a single column from the next row of a result set
    • PDOStatement->fetchObject — Fetches the next row and returns it as an object.
    • PDOStatement->getAttribute — Retrieve a statement attribute
    • PDOStatement->getColumnMeta — Returns metadata for a column in a result set
    • PDOStatement->nextRowset — Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
    • PDOStatement->setAttribute — Set a statement attribute
    • PDOStatement->setFetchMode — Set the default fetch mode for this statement

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.