2012-06-27 108 views
0

請參閱下面的代碼。我試圖從數據庫中獲取一些數據是modx。數據在那裏,這意味着,當我在phpmyadmin中查詢數據庫時,我得到了結果。我無法弄清楚爲什麼它在modx中不起作用。MODx查詢自定義數據庫表

$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1'; 

$stmt = $modx->prepare($sql); 
$stmt->execute(); 

// Put data in array 
$order_data = $stmt->fetch(PDO::FETCH_ASSOC); 
if ($order_data == '') { 
    return 'Resultset empty for user '. $user_id.'.<br />'.$sql; 
} else { 
    return 'Data found!'; 
} 
+0

這是從一個自定義的第三方組件?你是否在數據庫中爲這個字段創建了一個對象? – OptimusCrime

+0

是的,是的,但我也需要它爲在modx中沒有對象的自定義數據庫表工作。我從這個網頁得到了這個:http://forums.modx.com/thread/35321/querying-a-non-modx-table-in-revolution – Meddie

+0

嘗試用'PDO_FETCH_ASSOC'切換'PDO :: FETCH_ASSOC'?你有任何錯誤? – OptimusCrime

回答

0

也許嘗試使用xPDO:

$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1'; 

$c = new xPDOCriteria($modx,$sql); 
if ($c->stmt && $c->stmt->execute()) { 
    $order_data = $c->stmt->fetch(PDO::FETCH_ASSOC); 
    var_dump($order_data); 
} 
0

您可以通過您的輸出需要循環,其結果將是一個數組的數組。

下面的例子將返回數據,並根據塊格式

<?php 
$sql = "SELECT * FROM `table_name`"; 
$query = $modx->query($sql); 
$rows = array(); 
if ($query) { 
    // loop through the result set and inspect one row at a time 
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) { 
     array_push($rows, $row); 
     $output .= $modx->getChunk($tpl,$row); 
    } 
} 
$output = "<table border=\"1\" cellpadding=\"5\" > 
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th> 
$output</table>"; 
return $output; 

這目前只是一個塊的例子:

<tr> 
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td> 
</tr> 

現在在資源打電話給你像

[[!Snippet_name? &tpl=`chunk_name`]] 
+0

或者也許你可以按照這裏自己的指導: http://rtfm.modx.com/revolution/2.x/case-studies-and-tutorials/using-custom-database-tables-in-your-3rd-黨的組件 –

0
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1'; 

假設你的模式是一樣

<?xml version="1.0" encoding="UTF-8"?> 
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1"> 
    <object class="Orders" table="orders" extends="xPDOSimpleObject"> 
     <field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" /> 
     <!-- and everything else below --> 

    </object> 

    <!-- and everything else below --> 
</model> 

你需要做的是如此簡單:

$modx->addPackage('your_package_name'); // Add your table schema to MODX object 

$orders = $modx->getCollection('Orders'); // class's name, not table's name 
$output = ''; 
if ($orders){ 
    $outputArray = array(); 
    foreach ($orders as $order) { 
     $orderArray = $order->toArray(); 
     $outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray); 
    } 
    $wrapper = array(
     'orders' => @implode("\n", $outputArray); 
    ); 
    $output = $modx->getChunk('your_wrapper_chunk_name', $wrapper); 
} 

return $output;