ThingEngineer / PHP-MySQLi-Database-Class

Wrapper for a PHP MySQL class, which utilizes MySQLi and prepared statements.
Other
3.3k stars 1.34k forks source link

Get greatest Value #1024

Closed JuliusFroglet closed 6 months ago

JuliusFroglet commented 11 months ago

Hi, how do I get the row with a columns greatest value?

I thoght it could work like this, but unfotunately... no effect.

$db->get($tables["dates"],"greatest(start)");

this also won't work

$db->get($tables["dates"],"max(start)");

Any ideas, who to get this running?

huseyinaslim commented 10 months ago

Hi @JuliusFroglet ,

The library's get function is designed to list multiple lines, and upon examination, you can see that the second parameter of this function is used to modify the LIMIT statement in order to limit the number of returned results.

    /**
     * A convenient SELECT * function.
     *
     * @param string       $tableName The name of the database table to work with.
     * @param int|array    $numRows   Array to define SQL limit in format Array ($offset, $count)
     *                                or only $count
     * @param string|array $columns   Desired columns
     *
     * @return array|MysqliDb Contains the returned rows from the select query.
     * @throws Exception
     */
    public function get($tableName, $numRows = null, $columns = '*')

In your code, however, the second parameter is used to indicate the column name. This is an incorrect usage. If we want to filter columns with the get function, you should demonstrate a usage like this:

We should use it in this way;

$db->get($tables["dates"], null, "greatest(start)");  

$db->get($tables["dates"], null, "max(start)");  

However, functions like GREATEST, MAX return only a single row result, so using getOne instead of get may be more ideal. In fact, if you want to obtain only a single column, using getValue is the most ideal.

I recommended it for example;

$db->getOne($tables["dates"], "id, greatest(start)");  
$db->getValue($tables["dates"], "greatest(start)");  

$db->getOne($tables["dates"], "id, max(start)"); 
$db->getValue($tables["dates"], "greatest(start)");