Php和PDO - 获取数据

时间:2018-05-19 22:06:34

标签: php mysql pdo

有人可以告诉我为什么以下不起作用:

$result = $this->db->prepare("SELECT high,low FROM data where symbol=:symbol and date1 <= :date1 order by date1 desc LIMIT :limit1");
    $result->bindParam(':symbol', $total_pairs, PDO::PARAM_STR);
    $result->bindParam(':date1', $date1, PDO::PARAM_STR);
    $result->bindParam(':limit1', $period, PDO::PARAM_INT);
    $result->execute();

    $data = $result->fetchAll(PDO::FETCH_ASSOC);


   var_export($data["high"]);

这给了我错误:

 Undefined index: high

我正在尝试获取两列并在数组中获取结果。

2 个答案:

答案 0 :(得分:0)

$ data数组包含多个关联数组(每个记录返回一个)。如果你只想要一个数组中每个记录的高值,而只想要另一个结果集中的低值,你可以这样做:

<?php

$high = array_column($data, 'high');
$low = array_column($data, 'low');

?>

答案 1 :(得分:0)

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

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->name;
print("\n");
?>

它可以帮助您更好地理解。此代码取自php.net网站