-1

I'm trying to create a query but it doesn't work. Where am I wrong ?

$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();
  • You probably should use double quotes. Other than that, please prepare your statement instead of trusting your data is mysql safe. –  May 18 '17 at 08:55
  • 1
    Have you tried examining the error that you get and see what's going on? Your intention is to use the value of the date variable but you have embedded it as part of the SQL text. – Raam May 18 '17 at 08:56

3 Answers3

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();

Make sure you bind the variables to your query instead of directly inserting your data into your query, this is considered as unsafe. More info about this can be found in the manual

Nimantha
  • 6,405
  • 6
  • 28
  • 69
1

The reason your query is failing is because you are trying to reference your variables in a string created with apostrophes, this only works with double quotes!

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

You should also prepare the query properlyas in the 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();

By using prepared statements like this, you are protected against SQL injection because the query isn't parsed in the same way.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34
-1

You need to use the concatenation operator in your SQL query. http://php.net/manual/en/language.operators.string.php

Like this

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

EDIT -> credits goes to @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();
Azoel
  • 209
  • 6
  • 19