When I'm doing this foreach loop perfectly works.
<?php
function checkInDB($NIC){
$user='root';
$pass='123';
$db='mysql:host=localhost;dbname=recruit';
$dbh= new PDO($db,$user,$pass);
$sql = 'SELECT FirstName
FROM cv
JOIN candidate ON cv.cvID=candidate.cvID
WHERE ((submittedDate > NOW() - INTERVAL 365 day)
AND (candidate.NIC="906548765V"))';
echo '<h3>candidates</h3>', '<hr />', PHP_EOL;
echo '<table border=1>', PHP_EOL;
foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
echo '<tr><td>', implode('</td><td>', $row), '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}
checkInDB("906548765V");
?>
but when I just changing (candidate.NIC="906548765V")
to (candidate.NIC=$NIC)
which even makes echo ($NIC==="906548765V");
true, throws an unexpected error
Invalid argument supplied for foreach()
What exactly is happening there?
In PHP there are 2 kind ways to define a string:
When you use Single quotes, the string will be as defined. When using double quotes, PHP will parse the string.
Then on another note. Never ever include a variable into a query string. Just don't. SQL injection and all that. ALWAYS use prepared statements. You are using PDO, so it's easy: