Jeff Chew
Jeff Chew

Reputation: 29

How to return error message if there is no data in the database?

I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.

Here is my code:

$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
    echo 'No data found in database!';
} else {
    return $data = $query;
}

Before this code, if the code that query from database:

//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
    $query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}

I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.

The script below:

//create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
    $r1          = $row->rowone;
    $r2          = $row->rowtwo;
    $r3          = $row->rowthree;
    $englishdate = $row->dob_eng;
    $chinesedate = $row->dob_chi;
    
    //add all initial data into the matrix variable for easier access to them later
$rows[0]
    $rows = array(
        array($r1),
        array($r2),
        array($r3),
        array()
    );
    
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
    return ($a % $m) + 1;
}

//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
    //function to access the global variable.
    global $rows;
    $row = $rows[$rowId];
    while (sizeof($row) < $populationCount) {
        $rowInd = sizeof($row) - 1;
        $m      = incmod($row[$rowInd], $mod);
        array_push($row, $m);
    }
    
    //set the row back into the global variable.
    $rows[$rowId] = $row;
}

Upvotes: 1

Views: 2899

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157888

$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
    echo 'No data found in database!';
}

Upvotes: 2

Related Questions