2015-06-24 117 views
1

我從普通的MYSQL移到PDO MYSQL並開始使用預處理語句。用我的舊系統,我能夠查詢數據庫並將信息存儲在一個數組中。然後我會使用usort按金額對錶格進行排序。PDO結果到數組

由於我已經轉移到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"); 

這會導致表格按「現金」列排序。下面的代碼來自我的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) 
+1

爲什麼您選擇不使用ORDER BY在查詢中進行排序的具體原因是什麼? – RuubW

回答

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循環事後處理數據。

0

for循環更改到

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

修正這一點。