We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 49371
    • 6 Posts
    Hi Guys,

    I have a "scores" custom table.

    I want to update one row of this table.

      $c = $modx->newQuery('Score');
      $c->where(array('id' => 5));
      $c->fromArray(array(
            "myfield" => "this is the new value for myfield",
       ));
    


    The problem is I don't know how to write the code for the update query.

    In the manual I have found many examples of update queries, but all are using "$modx->getFullTableName("modx_table_scores")"
    I think it's not a good idea to update a table directly by its name.

    I prefer to use "$modx->newQuery('Score')", but I don't find nowhere how to update.

    Have a nice day with MODX smiley

    This question has been answered by multiple community members. See the first response.

    • discuss.answer
      Hiya!

      You'll need to get the object using the query, before you can manipulate the row. Something like this should work:

      $c = $modx->newQuery('Score');
      $c->where(array('id' => 5));
      
      $score = $modx->getObject('Score', $c);
      
      if ($score) {
        $score->fromArray(array(
          'myfield' => 'new value for myfield'
         ));
        $score->save();
      }


      However, as you're only filtering on the ID, you could use this shortcut and skip creating the query:
      $score = $modx->getObject('Score', 5);
      if ($score) { 
         //...
      }
        Mark Hamstra • Developer spending his days working on Premium Extras and a MODX Site Dashboard with the ability to remotely upgrade MODX and extras to make the MODX world a little better.

        Tweet me @mark_hamstra, check my infrequent blog at markhamstra.com, my slightly more frequent ramblings at MODX.today or see code at Github.
      • discuss.answer
        • 3749
        • 24,544 Posts
        You can also just retrieve the object as Mark suggests, then site a single field or multiple fields with set(), then save it:

        $score = $modx->getObject('Score', 5);
        if ($score) {
           $score->set('fieldName', $value);
           $score->save();
        }


          Did I help you? Buy me a beer
          Get my Book: MODX:The Official Guide
          MODX info for everyone: http://bobsguides.com/modx.html
          My MODX Extras
          Bob's Guides is now hosted at A2 MODX Hosting
          • 49371
          • 6 Posts
          thanks Mark and Bob smiley