0

in sqlqry.php

function procat(){
    require_once("..\db.php");

    $procat = $DBH->prepare("SELECT pro_sr FROM products LEFT JOIN 
    categories ON products.pro_cat=categories.cat_sr");
    $procat->execute();
    while($rowprocat[]=$procat->fetch()) {}
    return $rowprocat;
}

in products.php

<?php 
    $rowprocat=procat(); 
    print_r($rowprocat); 
?>

Array ( [0] => Array ( [pro_sr] => 60 [0] => 60 ) [1] => Array ( [pro_sr] => 61 [0] => 61 ) [2] => Array ( [pro_sr] => 62 [0] => 62 ) [3] => )

why it is showing 4 rows whereas actually it has 3 records. also tested in phpMyAdmin shows 3. 4th row is empty.

Emraan Aly
  • 135
  • 1
  • 2
  • 7
  • because you are feeling a smart aleck and trying to save yourself writing a line of code – Your Common Sense Mar 06 '18 at 13:26
  • sorry for what I wrote earlier on your above comment. my question was different than what you assumed. i got crazy when you tagged as duplicate and closed. Great responsibility comes with great power. Once again sorry. – Emraan Aly Mar 06 '18 at 16:16

1 Answers1

0

Because you are assigning the return value of $procat->fetch() to an array, no matter if there was a result or not.

This is why most people use a temporary variable in that case in PHP:

function procat(){
    require_once("..\db.php");

    $procat = $DBH->prepare("SELECT pro_sr FROM products LEFT JOIN 
    categories ON products.pro_cat=categories.cat_sr");
    $procat->execute();
    while($row = $procat->fetch()) {
        $rowprocat[] = $row;
    }
    return $rowprocat;
}
feeela
  • 29,399
  • 7
  • 59
  • 71
  • Thanks @feeela. fetchAll helped me. I also tried your way and it is also working good. thanks a lot to people like you try to help others. – Emraan Aly Mar 06 '18 at 13:43
  • @EmraanAly Be aware, that if you handle huge amounts of data, `fetchAll` will load it all at once into the memory, while `fetch` loads only one line of the result per call. Thus using `fetch` properly result usually in faster and lightweighter scripts. – feeela Mar 06 '18 at 13:48
  • at present i have just 3 rows but later i guess maximum 1000 rows (with 20+ columns). yes loading time matters. is there anyway to test time consumption of both? Sorry if becoming pest. :) Thanks for all what you educated me. – Emraan Aly Mar 06 '18 at 16:13
  • To tell you truth, your code does the same as fetchAll. even loading one result per call – Your Common Sense Mar 06 '18 at 18:26
  • and, given you are selecting your data for a human, his cognitive ability would be a bottleneck, not the server's memory. for a script, 2k rows is nothing, but a human won't be able to read it – Your Common Sense Mar 06 '18 at 18:28
  • @YourCommonSense yes my code was doing the same as fetchAll but adding an extra empty row that's why I asked which you mentioned as duplicate. anyways, now I have 2 ways to handle this. Thanks everyone. – Emraan Aly Mar 06 '18 at 18:43