在mysql php7中用变量创建一个查询?

时间:2017-05-18 08:53:48

标签: php mysql pdo

我正在尝试创建一个查询,但它不起作用。 我哪里错了?

$date = new \Datetime(date('d-m-Y'));
$date->add(DateInterval::createFromDateString('- 2 day'));
$date = $date->format('Y-m-d');

$stmt = $pdo->prepare('SELECT company.id as id, email, first_name, last_name, slug FROM company WHERE created < $date AND reminder = 0');

$stmt->execute();
$result = $stmt->fetchAll();

3 个答案:

答案 0 :(得分:2)

正确的方法(未经测试):

$date = new \Datetime(date('d-m-Y'));
$date->add(DateInterval::createFromDateString('- 2 day'));
$date = $date->format('Y-m-d');

$stmt = $pdo->prepare('SELECT company.id as id, email, first_name, last_name, slug FROM company WHERE created < :date AND reminder = 0');
$stmt->bindParam(':date', $date);

$stmt->execute();
$result = $stmt->fetchAll();

确保将变量绑定到查询而不是直接将数据插入查询,这被视为不安全。 有关此内容的更多信息,请参阅manual

答案 1 :(得分:1)

您的查询失败的原因是您尝试在使用撇号创建的字符串中引用变量,这仅适用于双引号!

$myvar = 1234;
$q1 = 'myvar = $myvar'; // myvar = $myvar
$q2 = "myvar = $myvar"; // myvar = 1234

您还应该在PHP docs

中正确准备查询
$date = new \Datetime(date('d-m-Y'));
$date->add(DateInterval::createFromDateString('- 2 day'));
$date = $date->format('Y-m-d');

$stmt = $pdo->prepare("SELECT company.id as id, email, first_name, last_name, slug FROM company WHERE created < :date AND reminder = :reminder");

$stmt->execute([':date' => $date, ':reminder' => 0]);
$result = $stmt->fetchAll();

通过使用这样的预处理语句,可以防止SQL注入,因为查询不会以相同的方式解析。

答案 2 :(得分:-1)

您需要在SQL查询中使用连接运算符。 http://php.net/manual/en/language.operators.string.php

像这样

$stmt = $pdo->prepare('SELECT company.id as id, email, first_name, last_name, slug FROM company WHERE created < "' . $date . '" AND reminder = 0'); 

<击>

编辑 - &gt;学分转到@SheperdOfFire:

$date = new \Datetime(date('d-m-Y'));
$date->add(DateInterval::createFromDateString('- 2 day'));
$date = $date->format('Y-m-d');

$stmt = $pdo->prepare('SELECT company.id as id, email, first_name, last_name, slug FROM company WHERE created < :date AND reminder = 0');
$stmt->bindParam(':date', $date);

$stmt->execute();
$result = $stmt->fetchAll();