Chris Mccabe
Chris Mccabe

Reputation: 1951

How to escape single quotes in Laravels DB::select binding

Laravel adds single quotes around my orderBy which is causing the query to not execute as expected

I have tried numerous combinations of using DB::raw while trying to remove the single quotes from my select statement and got nowhere.

<?php
$sql = "SELECT cust_name, ad_text, total_sms FROM customers WHERE created_at > :startDate AND created_at < :endDate ORDER BY :orderBy DESC;";

return DB::Select($sql, ['startDate'=>$startDate,'endDate'=>$endDate, 'orderBy' => $orderBy]);?>

which comes out to

ORDER BY 'total_sms' DESC;

How do i escape this binding param so its single quotes are removed?

Upvotes: 2

Views: 2604

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Another good way is

  DB::table("customers as c")
  ->whereBetween("created_at",[$start_date, $end_date])
  ->select("cust_name", "ad_text", "total_sms")
  ->orderBy($orderBy,"Desc")
  ->get();

Upvotes: 0

CoursesWeb
CoursesWeb

Reputation: 4237

Add columns name between " ` " sign, not " ' ".

  • To escape single quotes, use: str_replace("'", "\\'", $str)

Upvotes: 3

Related Questions