如何使用 PDO 在 PHP 中获取结果数组? [英] How can I use PDO to fetch a results array in PHP?

查看:29
本文介绍了如何使用 PDO 在 PHP 中获取结果数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了SQL 注入 攻击后,我正在编辑我的搜索脚本.我正在尝试使用 PDO 而不是 a常规 MySQL 连接.所以我一直在阅读有关 PDO 的其他帖子,但我不确定.这两个脚本会提供相同的功能吗?

I'm just editing my search script after reading up on SQL injection attacks. I'm trying to get the same functionality out of my script using PDO instead of a regular MySQL connection. So I've been reading other posts about PDO, but I am unsure. Will these two scripts give the same functionality?

使用 PDO:

$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);

使用常规 MySQL:

With regular MySQL:

$dbhost = @mysql_connect($host, $user, $pass) or die('Unable to connect to server');

@mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);

$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";

if(!isset($query)){
    echo 'Your search was invalid';
    exit;
} //line 18

$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);

我继续使用常规示例

while($i < $numrows){
    $row = mysql_fetch_array($result);

从数据库创建匹配结果的数组.如何使用 PDO 执行此操作?

to create an array of matching results from the database. How do I do this with PDO?

推荐答案

查看PDOStatement.fetchAll 方法.您还可以在迭代器中使用 fetch模式.

fetchAll 的代码示例,来自 PHP 文档:

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

结果:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

这篇关于如何使用 PDO 在 PHP 中获取结果数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆