[solved][xpdo] How can I save an array into a table?

Hello,

I would like to update the “count_items” fields for each row in the “categories” table

Can someone help me with the following portion of code? Why can’t I save $rows?

$c = $modx->newQuery( $categoriesTable );
$c->select( $modx->getSelectColumns( $categoriesTable, $categoriesTable ) );
$c->prepare();

if ( $c->stmt->execute() ) {

    if ( !$rows = $c->stmt->fetchAll( PDO::FETCH_ASSOC ) ) {

        $rows = array();

    }

}

foreach ( $rows as $i => $row ) {

	$rows[ $i ][ 'count_items' ] = countItems( $i, $modx );

}

$rows->save();

The last line gives:“Fatal error: Uncaught Error: Call to a member function save() on array”

How can I convert $row into a format that I would be able to save?

Thank you for the help

To update your data, it is probably a better idea to use getIterator or getCollection.

$categories = $modx->getIterator($categoriesTable);
foreach ($categories as $category) {
    $category->get('count_items'); //read the value of 'count_items'
    $category->set('count_items', 'new value'); // set 'count_items' to a new value
    $category->save();
}
1 Like

It works perfectly with an iterator, thank you for your help!