equaling the PHP argument and mysql data makes foreach loop not work

73 views Asked by At

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?

2

There are 2 answers

2
Pinoniq On BEST ANSWER

In PHP there are 2 kind ways to define a string:

  • Double quotes
  • Single quotes

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:

$stmt = $dbh->prepare('SELECT cols FROM table WHERE col1 = :myCol1Value');
$stmt->bindParam('myCol1Value',$theActualValue);
$stmt->execute();
2
Markus On

try AND (candidate.NIC="'.$NIC.'") since it's a string you still need the quotes.