Skip to content
Advertisement

Pulling Queries from Database Clears Results on Error vs. Stopping

We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don’t want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?

Connection to Database:

<?php

$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';

try {
    $db = new PDO($constr, $dbUser, $dbPW);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    //$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $rez = "Connected";
    //echo $rez;
} catch(PDOException $ex) {
    $rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
    //echo $rez;
}

?>

Code to display the results on the page:

<?php

    include 'db.connect.php';

    $sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";

    $stmt = $db->prepare($sql);
    $stmt->execute();
    $num_rows = $stmt->rowCount();
    //echo $num_rows;

    if($num_rows > 0) {

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            $id =  $row['ts_id'];
            $name  = $row['name'];

            echo "<tr>";
            echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";

            echo "</tr>";

        }

    } else {

        echo "<tr>";
        echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
        echo "</tr>";

    }

    include 'db.close.php';

?>

Thank you in advance!

Advertisement

Answer

You might try changing your query to:

$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";

I don’t know if that will filter out your error message

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement