SiliconMachine
SiliconMachine

Reputation: 606

Cannot use PHP var in a SQL Query

I'm trying to show each row where userCZ = $_SESSION['user'], but whenever I try with the var, it doesn't find nothing at all. If I replace the var for a literal string, It works perfectly. I've also tried to check if the var is not empty and it returns the proper value at the begin of the script. I think I am missing something in the syntax but I've tried with '' and "" and still not working.

<?php
  session_start();
  $userCZ=$_SESSION['user'];


require_once __DIR__ . "/../../init.php";
require_once __DIR__ . "/../../functions/db.php";

if (isset($_GET['start']) && isset($_GET['end'])) {
$stmt = 'SELECT * FROM the_events WHERE userCZ = '$userCZ' AND start_date >= 
:start and end_date <= :end';
$_events = QuickPdo::fetchAll($stmt, [
    'start' => $_GET['start'],
    'end' => $_GET['end'],
]);



$events = [];
foreach ($_events as $e) {
    $events[] = [
        'id' => $e['id'],
        'title' => $e['title'],
        'project' => $e['project'],
        'start' => dateMysqlTime2Iso8601($e['start_date']),
        'end' => dateMysqlTime2Iso8601($e['end_date']),
    ];
}
echo json_encode($events);
}

Upvotes: 0

Views: 54

Answers (1)

tadman
tadman

Reputation: 211560

This can be addressed by binding all of the dynamic values:

$_events = QuickPdo::fetchAll(,
  'SELECT * FROM the_events WHERE userCZ = :userCZ AND start_date >= :start and end_date <= :end',
  [
    'userCZ' => $userCZ,
    'start' => $_GET['start'],
    'end' => $_GET['end'],
  ]
);

Avoid using string interpolation unless you have no other option, and when that occurs, take every possible precaution to ensure you're doing it safely.

Upvotes: 2

Related Questions