PDO结果到阵列

时间:2015-06-24 07:07:01

标签: php mysql arrays pdo

我从简单的MYSQL转移到PDO MYSQL并开始使用预准备语句。使用我的旧系统,我能够查询数据库并将信息存储在数组中。然后我会使用usort按金额对表格进行排序。

由于我已经转移到PDO,我在使用数组时遇到了问题,因此我摆脱了它。我的原始代码如下:

$sql = "SELECT name, item, cash, props FROM Donators";
$result = $conn->query($sql);
$result_array = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $result_array[] = $row;
        //var_dump($result_array);
    }
} else {
    echo "You have yet to join our servers!";
}
$conn->close();

function custom_sort($a,$b) {
    return $a['cash']<$b['cash'];
 }
usort($result_array, "custom_sort");

这导致表格按照&#39; cash&#39;列进行排序。下面的代码来自我的PDO代码。

    try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT name, item, cash, props FROM Donators"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    $result_array = array();
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
       $result_array[$k] = $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

function custom_sort($a,$b) {
    return $a['cash']<$b['cash'];
 }
//print_r($result_array);
usort($result_array, "custom_sort");
$length = count($result_array);

usort会导致此错误:

Warning: Illegal string offset 'cash'

打印数组$ result_array显示

Array ( [name] => Жэка90 [item] => none [cash] => 1000 [props] => 0 )

2 个答案:

答案 0 :(得分:0)

将for循环更改为

foreach($stmt->fetchAll() as $k=>$v) { 

修正了此问题。

答案 1 :(得分:0)

我使用以下代码:

// In case an error occured during statement execution, throw an exception
if (!$stmt->execute()) {
    // Error handling with $stmt->errorInfo()
}

// Fetch all results
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

之后不需要foreach循环来处理数据。