catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

How to use function in select statement in the right way ? #76

Closed Rolaka closed 10 years ago

Rolaka commented 10 years ago
$news = $database->get('article', array(
    'id',
    'title',
    'DATE_FORMAT(date, "%m-%d-%Y")'
), array(
    'type' => 'news',
    'LIMIT' => '7'
));

->

SELECT "id","title","DATE_FORMAT(date, "%m-%d-%Y")" FROM "article" WHERE "type" = 'news' LIMIT 7

QAQ...

PS: Had no choice, My dirty patch:

    protected function column_quote($string)
    {
        if($string[0] == '~')
        {
            return substr($string, 1, strlen($string)-1) ;
        }
        else
        {
            return '"' . str_replace('.', '"."', $string) . '"';
        }
    }

Use this format...

$news = $database->select('article', array(
    'id',
    'title',
    '~DATE_FORMAT(date,\'%m-%d-%Y\') AS "date"'
), array(
    'type' => 'news',
    'LIMIT' => '7'
));
SELECT "id","title",DATE_FORMAT(date,'%m-%d-%Y') AS "date" FROM "article" WHERE "type" = 'news' LIMIT 7
catfan commented 10 years ago

It`s not recommend to use SQL inbound function for SQL query that PHP native function can do it as well.

Rolaka commented 10 years ago

ic, thx catfan fix the "now()" \QAQ//

Adoniasv commented 10 years ago

if change this, table alias "alias(tname)" for "alias[date_format(table,'xxx')]" works

protected function column_push( $columns )
{
    if ( $columns == '*' ) {
        return $columns ;
    }

    if ( is_string( $columns ) ) {
        $columns = array( $columns ) ;
    }

    $stack = array() ;

    foreach ( $columns as $key => $value ) {
        preg_match( '/([a-zA-Z0-9_\-\.]*)\s*\[((.*?)*)\]/i', $value, $match ) ;

        if ( isset( $match[1], $match[2] ) ) {
            array_push( $stack, $match[2] . ' AS ' . $match[1] ) ;
        } else {
            array_push( $stack, $this->column_quote( $value ) ) ;
        }
    }

    return implode( $stack, ',' ) ;
}
shijianzhiwai commented 6 years ago

use this

$news = $database->get('article', array(
    'id',
    'title',
    'asName'=>Medoo\Medoo::raw('DATE_FORMAT(date, "%m-%d-%Y")')
), array(
    'type' => 'news',
    'LIMIT' => '7'
));