设置 | 登录 | 注册

作者共发了64篇帖子。

今天我来系统地学习一下PDO

22楼 巨大八爪鱼 2015-5-30 20:55
获取多条记录,并循环边历记录集
<?php
$sql = "SELECT ItemName, ItemAddress FROM WiFiHotSpots";
$stmt = $dbh->query($sql); // use $stmt instead of $rs or $result
foreach ($stmt as $row) {
    echo "<p><b>" . $row[0] . "</b>: " . $row["ItemAddress"]."</p>";
}
?>
23楼 巨大八爪鱼 2015-5-30 21:00
循环边历记录集可以用多种方法:
方法一:foreach ($stmt as $row) {
方法二:while ($row = $stmt->fetch()) {

甚至还可以指定次数:
for ($i = 0; $i < 4 && $row = $stmt->fetch(); $i++) {
    echo "<p><b>" . $row[0] . "</b>: " . $row["ItemAddress"]."</p>";
}
24楼 巨大八爪鱼 2015-5-30 21:01
while ($row = $stmt->fetch()) {
就相当于原来的:
while ($row = mysql_fetch_array($rs)) {

for ($i = 0; $i < 4 && $row = $stmt->fetch(); $i++) {
相当于
for ($i = 0; $i < 4 && $row = mysql_fetch_array($rs); $i++) {
25楼 巨大八爪鱼 2015-5-30 21:03
foreach ($stmt as $row) { 只能遍历整个记录集,要想指定次数就得改用$row = $stmt->fetch();
26楼 巨大八爪鱼 2015-5-30 21:11
从外部获取字符串参数并传入SQL查询中:
<?php
if (isset($_GET["name"])) {
    $name = trim($_GET["name"]); // 去掉字符串两边的空格
    $name = $dbh->quote($name); // 这个大致相当于原来的用于防止SQL隐码攻击的mysql_real_escape_string函数,但是这个函数两边自动加上了单引号
    //echo $name;
} else {
    $name = "Annerley Library Wifi";
}
$sql = "SELECT * FROM WiFiHotSpots WHERE ItemName = {$name}"; //注意不能再加单引号了
$stmt = $dbh->query($sql);
$row = $stmt->fetch();
echo "(" . $row["ItemLatitude"] . ", " . $row["ItemLongitude"] . ")";
?>

输出(-27.3739664, 153.078323)
27楼 巨大八爪鱼 2015-5-30 21:15
回复:26楼
看PHP官方文档下面的内容吧:
PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.
If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.
Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.
因此26楼所属的方法机不推荐使用,应该改用prepare+bind+execute方法。
28楼 巨大八爪鱼 2015-5-30 21:16
而且,不是所有数据库都兼容$dbh->quote
29楼 巨大八爪鱼 2015-5-30 21:19
改进后的26楼代码:
if (isset($_GET["name"])) {
    $name = trim($_GET["name"]);
} else {
    $name = "Annerley Library Wifi";
}

$sql = "SELECT * FROM WiFiHotSpots WHERE ItemName = ?";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($name));
$row = $stmt->fetch();
echo "(" . $row["ItemLatitude"] . ", " . $row["ItemLongitude"] . ")";
30楼 巨大八爪鱼 2015-5-30 21:20
注意,那个?同样不能再加单引号
31楼 巨大八爪鱼 2015-5-30 21:22
$sql = "SELECT * FROM WiFiHotSpots WHERE ItemName = ? AND ItemID > 2";
非变量可以直接写入数据库

内容转换:

回复帖子
内容:
用户名: 您目前是匿名发表。
验证码:
看不清?换一张
©2010-2025 Purasbar Ver3.0 [手机版] [桌面版]
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。