Level 56
So many things...
- Do not interpolate php variables into your query string. This can lead to SQL injection. Use query parameters. Search for SQL Injection to learn about it.
- Do not use unsanitized strings in like operators, unless you want your users to use
%and_to enhance their queries.
Try this:
$types = ['type1', 'type2', 'type3', 'type', 'type5', 'type6'];
$sql = vsprintf(<<<'SQL'
SELECT
IFNULL(ROUND(SUM(`b`.`revtotal`), 2), 0) AS `comrevenuew`,
IFNULL((
SELECT SUM(`daily_target`)
FROM `live_statsb`
WHERE
`type` IN (%s)
AND (`businessunit` LIKE ? OR `businessunit` LIKE ?)), 0) AS `goal`,
ROUND(IFNULL(ROUND(SUM(`b`.`revtotal`), 2), 0) / IFNULL((
SELECT SUM(`daily_target`)
FROM `live_statsb`
WHERE
`type` IN (%s)
AND (`businessunit` LIKE ? OR `businessunit` LIKE ?)), 0) * 100, 2) AS `per`
FROM (
SELECT `jobs`.`jobid` AS `jobscompleted`
FROM `jobs`
WHERE
`jobs`.`active` = 1
AND UPPER(`jobs`.`status`) = 'COMPLETED'
AND `jobs`.`businessunit` IN (
SELECT `businessunit`
FROM `live_statsb`
WHERE `type` IN (%s))
AND (`jobs`.`completedon` BETWEEN ? AND ?)
AND (`jobs`.`businessunit` LIKE ? OR `jobs`.`businessunit` LIKE ?)
) `a`
LEFT JOIN (
SELECT
`invoices`.`jobid` AS `injobid`,
SUM(`invoiceitems`.`total`) AS `revtotal`
FROM
`invoices`,
`invoiceitems`,
`incomeitems`
WHERE
`invoices`.`invoiceid` = `invoiceitems`.`invoiceid`
AND `invoiceitems`.`ledgerid` = `incomeitems`.`ledgerid`
AND `invoiceitems`.`active` = 1
GROUP BY
`invoices`.`jobid`) `b` ON `a`.`jobscompleted` = `b`.`injobid`
ORDER BY `a`.`jobscompleted` ASC
SQL, [
implode(',', array_fill(0, count($types), '?')),
implode(',', array_fill(0, count($types), '?')),
implode(',', array_fill(0, count($types), '?')),
]);
$sanitize = fn ($value) => Str::of($value)
->replaceMatches('/\s+/', ' ')
->trim()
->replace('\\', '\\\\\\')
->pipe(fn ($str) => \addcslashes($str->value(), '%_'))
->replace(' ', '%')
->wrap('%')
->value();
$records = DB::select($sql, [
...$types,
$sanitize($bu),
$sanitize($bu2),
...$types,
$sanitize($bu),
$sanitize($bu2),
...$types,
$startdate,
$enddate,
$sanitize($bu),
$sanitize($bu2),
]);
dd($records);
You'll need these imports on the top of your file:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
Good luck =)
1 like