Search code examples
phpsql

Search a PHP array for number of characters


I read some data from the database with the following command:

$klassenstufe = $DB->get_records_sql( "SELECT c.id, c.name, c.idnumber, c.description, cm.cohortid, cm.userid
FROM {cohort} AS c
INNER JOIN {cohort_members} AS cm
ON c.id = cm.cohortid
WHERE cm.userid = {$get_userid}
" );

As an example, with

$klassenstufe->name

I get two entries from the database.

  1. AK2030
  2. AK2030b

I want to count the character set and only get the one that has 7 characters (AK2030b).

If I have the right data set, I want to have the number once (2030) and the last letter (b) in 2 different variables.

The number and letter can vary.

What approach can I take?


Solution

  • You can do everything with a single query, which will filter the name field which must be exactly 7 characters, and use SUBSTRING and RIGHT to get the number and the last letter (assuming the number is always 4 characters at the same place in the string)

    $klassenstufe = $DB->get_records_sql("
    SELECT 
        c.id, 
        c.name, 
        c.idnumber, 
        c.description, 
        cm.cohortid, 
        cm.userid,
        SUBSTRING(c.name FROM 3 FOR 4) AS number_part, -- Extracts '2030'
        RIGHT(c.name, 1) AS last_letter -- Extracts 'b'
    FROM {cohort} AS c
    INNER JOIN {cohort_members} AS cm ON c.id = cm.cohortid
    WHERE cm.userid = {$get_userid}
    AND LENGTH(c.name) = 7
    ");
    

    With the aliases you'll get $klassenstufe->number_part and $klassenstufe->last_letter