We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 22656
    • 121 Posts
    Hi guys, using following to retrieve data from db, after finding the example on here.
    Not sure if im not looking at this right, however the "else" part of the code never gets executed when the recordset is empty.
    How so?

    I’m currently resorting to setting an extra flag in the while loop, like "recordset_flag=true" and then checking for it in the "else" part in order to print the error message. Where am i going wrong?



    $stmt = $modx->query(’SELECT * FROM `mytable` ORDER BY `name` ASC’);
    if ($stmt && $stmt instanceof PDOStatement) {
    while ($row= $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row[’name’];
    }
    }
    else {
    echo "NO RECORDS!";
    }

      • 22303 MODX Staff
      • 10,725 Posts
      Your "else" will only catch cases where the SQL statement could not be prepared (i.e. SQL syntax errors, etc.). You’ll need to check that you get anything back from fetch() to decide if there are no records.