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

标签 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以迭代器模式。

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

<?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 - 如何在 PHP 中使用 PDO 获取结果数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127745/

相关文章:

javascript - window.location = '' 不工作;

mysql - 我可以从 Windows MySQL Workbench 连接到 GCP CE VM 实例上的 MySQL 吗?

mysql - SQL请求多个左连接和null

PHP 将数组传递给 PDO bindParam

php - 在 password_hash 值上使用准备好的语句有什么意义吗?

php - Mongodb 嵌套数组搜索

php - 使用 Factual 的 PHP 错误

php - 从我的连接表获取数据

php - Mysql 将行显示为列

PHP/PDO 错误 : SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)