作者DarkKiller (System hacked)
看板PHP
标题Re: 请多用 PDO...
时间Sun May 26 08:52:40 2013
现在一般常常鼓励用 PDO 连 MySQL,主要的原因是 mysql_* 已经被 PHP 5.5+ 宣告
为 deprecated:
http://jp.php.net/manual/en/function.mysql-connect.php
另外还有 escape 的原因而被建议用 PDO。
※ 引述《DarkKiller (System hacked)》之铭言:
: 文章会有点长,我先贴范例:
整个 PDO 的文件可以参考
http://jp.php.net/manual/en/book.pdo.php 这边。
: <?php
: # Connect to database.
: $db = new PDO('mysql:dbname=mydb;host=mydbhost.example.com', 'user', 'pass');
new 是 constructor,文件是出自 PDO::__construct:
http://jp.php.net/manual/en/pdo.construct.php
第一个参数是 DSN,对於 MySQL 来说主要就是提供 dbname 与 host 两个参数:
http://jp.php.net/manual/en/ref.pdo-mysql.php
对於 SQLite 则包括了 file 与 memory 两种方式:
http://jp.php.net/manual/en/ref.pdo-sqlite.php
http://jp.php.net/manual/en/ref.pdo-sqlite.connection.php
# memory 的方式,"sqlite:" 与 ":memory:" 的结合,所以中间是 "::" 没错:
$db = new PDO('sqlite::memory:');
# file 的方式:
$db = new PDO('sqlite:/tmp/test.sq3');
: # Use prepare() to generate PDOStatement object.
: $p = $db->prepare('SELECT * FROM `user` WHERE `id` = ?;');
刚开始用 PDO 的人会比较不习惯的地方,使用 PDO 时如果要取得资料,需要先产生
PDOStatement 物件。
: # Use execute() to run it.
: $p->execute(array(1));
然後再对 PDOStatement 物件带入参数。
: # Then fetch it, return object.
: $obj = $p->fetch(PDO::FETCH_OBJ);
接下来才是对物件取出资料。
: # Use property to access.
: printf("ID: %d\n", $obj->id);
: printf("Username: %s\n", $obj->username);
这边是说明用 PDO::FETCH_OBJ 取得的资料可以物件的方式存取。
: # Execute again, with id = 2.
: $p->execute(array(2));
同一个 PDOStatement 可以再次 execute。
: # We want array this time.
: $a = $p->fetch(PDO::FETCH_ASSOC);
然後再拉资料出来。
: # Use array to access.
: printf("ID: %d\n", $a['id']);
: printf("Username: %s\n", $a['username']);
这次是说明用 PDO::FETCH_ASSOC 取出来後可以用 array 的方式存取。
: # Generate another PDOStatement object.
: $p2 = $db->prepare('INSERT INTO `user` SET `id` = ?, `username` = ?;');
这边是示范多参数。
: # Insert it.
: $p2->execute(array(1, 'gslin'));
: # Again.
: $p2->execute(array(2, 'in2'));
然後执行两次。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 112.121.80.241