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

    I'm using the script below to insert "trigger" records into a table.
    Existence of such record prevents the server from running redundant activity somewhere else.

    $sqlCalcStatus2 = $modx->db->query("SELECT 1 FROM `cg_celeb_calculation_status` WHERE (CelebID = '$CelebID')");
    $resultCalcStatus2 = $modx->db->getRow($sqlCalcStatus2);
    
      if (!$resultCalcStatus2)
      {
        $fields = array('CelebID'	=> $CelebID);
        $modx->db->insert( $fields, 'cg_celeb_calculation_status' );
      }
    


    However, I'm getting occasional and inconsistent error messages from MODx about an attempt to insert duplicate CelebID value:
    « MODX Parse Error »
    MODX encountered the following error while attempting to parse the requested resource:
    « Execution of a query to the database failed - Duplicate entry '328887' for key 'PRIMARY' »
    SQL > INSERT INTO cg_celeb_calculation_status (`CelebID`) VALUES('328887')

    Can someone propose a better mean to avoid insert if record already exists?

    Thanks a lot,
    Shlomo [ed. note: shlomot last edited this post 11 years, 10 months ago.]
      Cheers,
      Shlomo Tommer
      • 13428 ☆ A M B ☆
      • 1,031 Posts
      I would replace 1 with *
      $sqlCalcStatus2 = $modx->db->query("SELECT * FROM `cg_celeb_calculation_status` WHERE (CelebID = '$CelebID')");
      


      Is the CelebID field auto incremented? Then don't add it to $fields.
        • 27072
        • 76 Posts
        Thanks for your feedback, Jako.

        SELECT 1 is a very effective way to query the table by indices only, not needing access to the data table itself in order to retrieve values for all columns.

        CelebID is a referenced value in this table and not an incremented column.

        My question if actually: how would you write in MODx the following SQL Statement:

        INSERT cg_celeb_calculation_status cg1 (CelebID)
        WHERE NOT EXISTS (
        SELECT * FROM cg_celeb_calculation_status cg2
        WHERE cg1.CelebID = cg2.CelebID )

          Cheers,
          Shlomo Tommer
          • 13428 ☆ A M B ☆
          • 1,031 Posts
          $modx->db->query exists.