0

请参阅下面的代码。我正在尝试从数据库中获取一些数据是 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!';
}
4

3 回答 3

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`]]
于 2013-09-21T17:44:13.140 回答
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);
}
于 2012-06-27T23:34:13.147 回答
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;
于 2013-12-27T10:58:44.017 回答