Search elgg entities based on metadata name, with operand LIKE

I am using following code to return entities based on certain metadata name, with an operand LIKE. I need to know

  1. is this the best way to do that? 
  2. Is this safe so that input is properly sanitized and validated to prevent SQL injection vulnerabilities.
  3. How to use prepared statements with parameter binding to ensure a safer approach to query construction?
<?php
    $name = get_input("name", null, true);
    $query = get_input("query", null, true);
    if($name && $query){
        $db = elgg_get_config('dbprefix');
        $options["limit"] = 5;
        $options["metadata_name_value_pairs"][] = ["name" => "usertype", "value" => "driver"];
        $options["joins"] = "JOIN {$db}metadata em ON em.entity_guid = e.guid";
        $options["wheres"] = "em.name = '$name' AND em.value LIKE '%$query%'";
        echo elgg_list_entities($options);    
    }
?>
  • Which your Elgg version?

    Since Elgg 3 we use Doctrine DBAL for SQL queries.

  • Try this:

    $name = get_input('name', '');
    $query = get_input('query', '');
    
    echo elgg_list_entities([
         'types' => 'user',
         'metadata_name_value_pairs' => [
              [
                     'name' => 'usertype',
                     'value' => 'driver',
              ],
         ],
         'joins' => [
              new \Elgg\Database\Clauses\JoinClause('metadata', 'em',             function(\Elgg\Database\QueryBuilder $qb, $joined_alias, $main_alias) {
              return $qb->compare("{$joined_alias}.entity_guid", '=', 'e.guid', ELGG_VALUE_INTEGER));
             }),
         ],
         'wheres' => [
               function(\Elgg\Database\QueryBuilder $qb) use($name, $query) {
                  return $qb->merge([
                             $qb->compare('em.name', '=', $name, ELGG_VALUE_STRING),
                             $qb->compare('em.value', 'LIKE', '%$query%', ELGG_VALUE_STRING),
                   ], 'AND');
                },
          ],
          'limit' => 5,
    ]);

    On your questions:

    1 - Why not? Just use a new way ;)

    2 - Absolutely if you follow Elgg's code standards.

    3 - Look at my example and the existing core and plugins' code. Ask here or welcome to Elgg chat in Telegram. We've a channel also.

Beginning Developers

Beginning Developers

This space is for newcomers, who wish to build a new plugin or to customize an existing one to their liking