您可能已经猜到语法了,下面给出了一个例子:
# the first argument is the named placeholder name - notice named # placeholders always start with a colon. $STH->bindParam(':name', $name);
您也可以在这里使用一个快捷方式,但它可以和关联数组一起使用.
# the data we want to insert $data = array( 'name' => 'Cathy', 'addr' => '9 Dark and Twisty', 'city' => 'Cardiff' );
# the shortcut! $STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)"); $STH->execute($data);
你的数组中的键不需要以一个冒号开始,但是必须符合指定的占位符。如果你有一个二维数组(就是数组中的数组),您可以遍历它们,只需调用执行的每个数据的数组。
另一个命名占位符不错的特点是直接可以插入对象到您的数据库,如果命名的属性匹配字段的话.下面是一个例子对象:
# a simple object class person { public $name; public $addr; public $city;
function __construct($n,$a,$c) { $this->name = $n; $this->addr = $a; $this->city = $c; } # etc ... }
$cathy = new person('Cathy','9 Dark and Twisty','Cardiff');
# here's the fun part: $STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)"); $STH->execute((array)$cathy);
在执行中,对象被转换为一个数组.对象的属性被视为数组中的一个键. By casting the object to an array in the execute, the properties are treated as array keys.
选择数据
数据通过fetch()方法获得, {一种应用于陈述式句柄的方法}. 在使用fetch之间, 您最好告诉PDO您喜欢取得数据的样子. 您有以下几个选择: