0

I'm trying to pull apart an imported csv file, and then each line, check if it exists in the database, for some reason I am getting 'doesnt exist' on every entry, even though the first entry is in fact in the database and should return 'exists'.

if(isset($_GET['uploadfile'])){
    $file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
    while(! feof($file)){
        $line = fgetcsv($file, 0, ',');

        list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;

        $sqlcheck = <<<SQL
    SELECT `productcode` FROM `stock` WHERE `productcode` = '$productcode'
    SQL;
    if(!$result = $db->query($sqlcheck)){ 
        echo $productcode.'exists';
        }
        else {
            echo $productcode.'doesnt exist';                   
        }

What is printed onto the screen is TEST1doesnt existsTEST2doesnt existsTEST3doesnt existsTEST4doesnt exists , but what is should say is TEST1 exists ?.

mymiracl
  • 583
  • 1
  • 16
  • 24
Iain Simpson
  • 441
  • 4
  • 13
  • 29
  • http://php.net/manual/en/function.error-reporting.php --- http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc - heredoc is failing you, if there are indeed spaces. – Funk Forty Niner Dec 26 '15 at 15:34
  • 1
    you need to use num_rows here. – Funk Forty Niner Dec 26 '15 at 15:40
  • 1
    http://php.net/manual/en/pdo.query.php a pdo statement object with zero results is evaluated as boolean true. Check the number of rows returned instead. And you might as well use prepared statement whilst you are at it. – Steve Dec 26 '15 at 15:52

1 Answers1

0
if(!$result = $db->query($sqlcheck)){ 
            echo $productcode.'exists';
                    }
                    else {
                        echo $productcode.'doesnt exist';                   
                        }

Isn't this backwards? If !$result means "doesn't exist". If $result means "exists".

Tim
  • 485
  • 2
  • 9