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

问题描述

在阅读了SQL注入攻击后,我只是在编辑搜索脚本.我正在尝试使用PDO而不是常规的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 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:

$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中获取结果数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:31