I am a beginner at PDO, I was making a php function to return search results of flights, this is my code:
$db = DB::getConnection();
$stmt = $db->prepare("SELECT * FROM `flights` WHERE `date` BETWEEN :befDate AND :aftDate
AND `from` = :from
AND `to` = :to
AND `weight` >= :weight");
$stmt->bindParam(':befDate', $befDate, PDO::PARAM_STR); //$befDate = '2016-07-21';
$stmt->bindParam(':aftDate', $aftDate, PDO::PARAM_STR); //$aftDate = '2016-07-28';
$stmt->bindParam(':from', $from, PDO::PARAM_INT);
$stmt->bindParam(':to', $to, PDO::PARAM_INT);
$stmt->bindParam(':weight', $weight, PDO::PARAM_INT);
$ok = $stmt->execute();
if ($ok) {
if ($stmt->fetchColumn()>=1) {
$result = $stmt->fetchAll();
}
else{
$result = 'nope';
}
return $result;
}
else{
return false;
}
The problem is, it is always returning 0 search results. I tried to run my SQL generated through function manually in phpMyAdmin and found that problem is because the SQL being generated by PDO is:
"SELECT * FROM `FLIGHTS` WHERE `DATE` BETWEEN 2016-07-17 AND 2016-07-25 AND `FROM` = 1237 AND `TO` = 2380 AND `WEIGHT` >= 4"
while the correct SQL from which I am getting results should be:
"SELECT * FROM `FLIGHTS` WHERE `DATE` BETWEEN '2016-07-17' AND '2016-07-25' AND `FROM` = 1237 AND `TO` = 2380 AND `WEIGHT` >= 4"
i.e, with date values between single quotes. Now if I add quotes to my SQL in PDO like:
$stmt = $db->prepare("SELECT * FROM `flights` WHERE `date` BETWEEN ':befDate' AND ':aftDate'
AND `from` = :from
AND `to` = :to
AND `weight` >= :weight");
I get "Invalid parameter number: number of bound variables does not match number of tokens" error. Thanks for you help in advance!
UPDATE:
My "flights" table structure is:
CREATE TABLE `flights` (
`fid` int(30) NOT NULL,
`user_id` int(30) NOT NULL,
`date` date NOT NULL,
`from` int(30) NOT NULL,
`to` int(30) NOT NULL,
`weight` int(30) NOT NULL,
`size` varchar(30) NOT NULL,
`details` varchar(200) NOT NULL,
`price` int(50) NOT NULL,
`airline` varchar(100) NOT NULL,
`pnr` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I tried removing all quotes from query and put it in a single unbroken line as well:
$stmt = $db->prepare("SELECT * FROM flights WHERE date BETWEEN :befDate AND :aftDate AND from = :from AND to = :to AND weight >= :weight");
but still it's not working...
UPDATE 2 To determine what the SQL statement looked like after binding params with PDO (the statement without single quotes) I made a session variable same as my SQL in the beginning of the function and echoed it to view result:
$_SESSION['err'] = "SELECT * FROM flights WHERE date BETWEEN $befDate AND $aftDate
AND from = $from
AND to = $to
AND weight >= $weight";