MODx查询自定义数据库表

时间:2012-06-27 13:28:31

标签: pdo modx

请参阅下面的代码。我试图从数据库中获取一些数据是modx。数据在那里,意思是,当我在phpmyadmin中查询数据库时,我得到了结果。我无法弄清楚为什么它在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!';
}

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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`]]

答案 2 :(得分: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;