不能在SQL查询中使用PHP var

时间:2017-10-10 01:22:51

标签: php mysql

我正在尝试显示每行 userCZ = $ _SESSION ['user'] ,但每当我尝试使用var时,它根本找不到任何内容。 如果我将var替换为文字字符串,它可以完美地工作。 我还尝试检查var是否为空,并在脚本开头返回正确的值。 我想我在语法中遗漏了一些内容,但我已尝试使用''和“”并仍然无法正常工作。

<?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);
}

2 个答案:

答案 0 :(得分:2)

这可以通过绑定所有动态值来解决:

$_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'],
  ]
);

除非您没有其他选择,否则请避免使用字符串插值,并且当发生这种情况时,请采取一切可能的预防措施以确保您安全地进行。

答案 1 :(得分:-1)

将您的sql语句更改为(注意使用单引号和双引号):

$stmt = "SELECT * FROM the_events WHERE userCZ = '$userCZ' AND start_date >= 
:start and end_date <= :end";

$stmt = "SELECT * FROM the_events WHERE userCZ = '{$userCZ}' AND start_date >= 
:start and end_date <= :end";