We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 25307
    • 114 Posts
    I’m getting the feeling I may be in over my head here trying to create a snippet using a MySQL query with multiple tables.. here’s an example of the query.. someone please show me the light...

    $wua = $modx->getFullTableName("web_user_attributes");
    $wg = $modx->getFullTableName("web_groups");
    $wgn = $modx->getFullTableName("webgroup_names");
    
    // query includes custom rows added to extend the web_user_attributes table
    $sql = 'SELECT `u`.`company`, `u`.`website`, `u`.`comment`, `u`.`address`, `u`.`city`, `u`.`state`, `u`.`zip`, `u`.`fullname`,' `u`.`phone`, `u`.`fax`, `u`.`mobilephone`, `u`.`email`';
    $sql .= 'FROM $wua AS `u` ';
    $sql .= 'LEFT JOIN `$wg` AS w ON `u`.`id` =  `w`.`webuser` ';
    $sql .= 'LEFT JOIN `$wgn` AS n  ON n.id =  `w`.`webgroup` ';
    $sql .= 'WHERE `u`.`type` = 1';
    $sql .= 'AND `u`.`company` LIKE  '%whatever%' ';
    $sql .= 'OR `u`.`type` = 1';
    $sql .= 'AND `n`.`name` LIKE '%whatever%' ';
    $sql .= 'ORDER BY `u`.`company` ASC ';
    
    $result = $modx->db->query($sql);
    


    thanks much if anyone can contribute any knoweledge, even if general enough for me to work through this...
      • 10449
      • 956 Posts
      Did you test the query outside of MODx?

      I see a ’ character after fullname that probably doesn’t belong there.

      Also, just a tip: use the handy heredoc syntax for multiline-strings/variables.

      $sql =<<<YOYOYO
      SELECT u.company, u.website, u.comment, u.address, u.city, u.state, u.zip, u.fullname, u.phone, u.fax, u.mobilephone, u.email
      FROM $wua AS u 
      LEFT JOIN $wg AS w ON u.id =  w.webuser 
      LEFT JOIN $wgn AS n  ON n.id =  w.webgroup 
      WHERE u.type = 1
      AND u.company LIKE '%whatever%' 
      OR u.type = 1
      AND n.name LIKE '%whatever%' 
      ORDER BY u.company ASC;
      YOYOYO
      

      instead of $sql .= "blah"; etc.
        • 25307
        • 114 Posts
        sweet, thanx for the tip - definitely beautifies that process and is saving me a chunk of time. =]