phpmysqllaravelselectwhere-in

How to pass external array to the query?


I am new to the mysql queries, i have one query which will search all the items inside the array status in ('php','laravel','apiato') if i use like this it's working, now i have to add more values to the array instead of passing strings i made one constant file from that file i want to send an array,it's throwing an exception Array To string Conversion

public function getALlData(){
$array = BooksConstants::Status_constants;
DB::select("SELECT count(1) as total_transactions from books  where books.account_id in ('$this->account_ids') and DATE(created_at) between ? and ? and status in $array ", [$fromDate, $toDate]);
}

Solution

  • First we use implode() to convert array to string then inside array_map() function use trim() function to remove whitespaces. The array_map() function sends each value of an array to a user-made function.

    public function getALlData()
    {
        $array = BooksConstants::Status_constants;
        DB::select(
            "SELECT count(1) as total_transactions
             from books
             where books.account_id in ('$this->account_ids')
                 and DATE(created_at) between ? and ?
                 and status in ('" . implode("','", array_map('trim', $array)) ."') ",
            [$fromDate, $toDate]
        );
    }