How do you embedded your sql queries in php scripts (coding-style)? How do you embedded your sql queries in php scripts (coding-style)? sql sql

How do you embedded your sql queries in php scripts (coding-style)?


Use a framework with an ORM (Object-Relational Mapping) layer. That way you don't have to put straight SQL anywhere. Embedded SQL sucks for readability, maintenance and everything.


Always remember to escape input. Don't do it manually, use prepared statements. Here is an example method from my reporting class.

public function getTasksReport($rmId, $stage, $mmcName) {    $rmCondition = $rmId ? 'mud.manager_id = :rmId' : 'TRUE';    $stageCondition = $stage ? 't.stage_id = :stageId' : 'TRUE';    $mmcCondition = $mmcName ? 'mmcs.username = :mmcName' : 'TRUE';    $sql = "            SELECT                    mmcs.id AS mmc_id,                    mmcs.username AS mmcname,                    mud.band_name AS mmc_name,                    t.id AS task_id,                    t.name AS task,                     t.stage_id AS stage,                    t.role_id,                    tl.id AS task_log_id,                    mr.role,                    u.id AS user_id,                    u.username AS username,                    COALESCE(cud.full_name, bud.band_name) AS user_name,                    DATE_FORMAT(tl.completed_on, '%d-%m-%Y %T') AS completed_on,                    tl.url AS url,                    mud.manager_id AS rm_id            FROM users AS mmcs            INNER JOIN banduserdetails AS mud ON mud.user_id = mmcs.id            LEFT JOIN tasks AS t ON 1            LEFT JOIN task_log AS tl ON tl.task_id = t.id AND tl.mmc_id = mmcs.id            LEFT JOIN mmc_roles AS mr ON mr.id = t.role_id            LEFT JOIN users AS u ON u.id = tl.user_id            LEFT JOIN communityuserdetails AS cud ON cud.user_id = u.id            LEFT JOIN banduserdetails AS bud ON bud.user_id = u.id            WHERE mmcs.user_type = 'mmc'                    AND $rmCondition                    AND $stageCondition                    AND $mmcCondition            ORDER BY mmcs.id, t.stage_id, t.role_id, t.task_order    ";    $pdo = new PDO(.....);    $stmt = $pdo->prepare($sql);    $rmId and $stmt->bindValue('rmId', $rmId); // (1)    $stage and $stmt->bindValue('stageId', $stage); // (2)    $mmcName and $stmt->bindValue('mmcName', $mmcName); // (3)    $stmt->execute();    return $stmt->fetchAll();}

In lines marked (1), (2), and (3) you will see a way for conditional binding.

For simple queries I use ORM framework to reduce the need for building SQL manually.


It depends on a query size and difficulty.

I personally like heredocs. But I don't use it for a simple queries.That is not important. The main thing is "Never forget to escape values"