Home > Back-end >  How a function can process multiple mysql results before returning?
How a function can process multiple mysql results before returning?

Time:12-29

i want to select each word from my mysql instead of all

function getItem($id)
{
    global $database;
    $stmt = $database->runQueryPlayer("SELECT vault FROM items WHERE index=?");
    $stmt->bindParam(1, $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if ($result)
        return get_item_name_locale_name($result[0]); // Each number will result a name
    else {
        return '---';
    }
}

must return all of them but separate.

my column looks like that, each number is item 78 26 50 28 -1 30 32 -1 -1 -1 -1 -1 0 0 0 0 0 0 0 0 0 0 0 0, because im using function get_item_name_locale_name, i should get

78 = name1
25 = name2
50 = name3

etc. but i get only first one. and i need to ignore -1 & 0 thank you

even if i using this query, result is the same, just first word

    SELECT hunter.a_index, hunter.a_name,f.a_wearing
FROM itemnames hunter
INNER JOIN vault f ON hunter.a_index = f.a_wearing
GROUP BY hunter.a_index

CodePudding user response:

I'm not familiar with Metin2CMS. But if the database layer is extending PDO, then the fetchAll call here should return an array of values.

Your issue is you're only returning the processed first result:

return get_item_name_locale_name($result[0]);

Instead, you should return an array of values all processed. You may use array_map for the purpose.

For PHP versions before 7.4:

function getItem($id)
{
    global $database;
    $stmt = $database->runQueryPlayer("SELECT vault FROM items WHERE index=?");
    $stmt->bindParam(1, $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if ($result) {
        // This is changed.
        return array_map(function ($row) {
            get_item_name_locale_name($row);
        }, $result);
    } else {
        return '---';
    }
}

For PHP 7.4 , you can use arrow function to shorten your code:

function getItem($id)
{
    global $database;
    $stmt = $database->runQueryPlayer("SELECT vault FROM items WHERE index=?");
    $stmt->bindParam(1, $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if ($result) {
        // This is changed.
        return array_map(fn($row) => get_item_name_locale_name($row), $result);
    } else {
        return '---';
    }
}

  • Related