php - 如何使用 PDO 在 PHP 中获取结果数组?

标签 php mysql pdo

我只是在阅读 SQL injection 后编辑我的搜索脚本攻击。我正在尝试使用 PDO 从我的脚本中获得相同的功能而不是常规的 MySQL 连接。所以我一直在阅读其他关于 PDO 的帖子,但我不确定。这两个脚本会提供相同的功能吗?

使用 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:

$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 做到这一点?

最佳答案

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

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

<?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
        )
)

关于php - 如何使用 PDO 在 PHP 中获取结果数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10911757/

相关文章:

PHP json_decode 不起作用

php - pcntl_fork() 中超过 300 秒的最大执行时间

php - 为什么我使用 PHP 发送邮件,但收件人收到附件名为 "mail.html"的邮件?

php - WordPress 错误 - 抱歉,您无权访问此页面。将网站从一个域迁移到另一个域后

php - pdo 查询未运行

mysql - 更适合我的查询的 MySQL 语法

php - 将 MySQL 数据库中的数据放入变量中

php - 无法获取要发布的 php mysqli while 语句

php - Joomla 中的简单 "loop"

php PDO 在脚本期间通过函数更改连接