内部计算的PDO查询的回声值

时间:2014-12-31 23:43:16

标签: php pdo

我刚刚将代码从使用mysqli_query更改为使用pdo,现在当我尝试使用$row[0]时,我得到了未定义偏移的结果。如何从PDO查询中获取值?

$pdo = new PDO("mysql:host=".$hostname.";dbname=saintfiv_artists", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)
    FROM royalties
    WHERE DATE BETWEEN '".$date2."' AND '".$date13."'
    GROUP BY DATE 
    ORDER BY DATE ASC");

if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
        {
         echo number_format($row[0], 2, '.', '') . ', ';
        }
    }

1 个答案:

答案 0 :(得分:1)

使用PDO,您可以在获取时获得一个数组,因此不需要while循环。假设查询中的两个变量是动态的,您还应该将它们参数化以确保安全性。尝试这样的事情:

$pdo = new PDO("mysql:host=".$hostname.";dbname=saintfiv_artists", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)
    FROM royalties
    WHERE DATE BETWEEN :date2 AND :date13
    GROUP BY DATE 
    ORDER BY DATE ASC";

$stmt = $pdo->prepare($query);
$stmt->execute(array(':date2' => $date2, ':date13' => $date13));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo '<pre>'; print_r($results); die();