3

If the result of the database exists, do this, if not, do this

 2 years ago
source link: https://www.codesd.com/item/if-the-result-of-the-database-exists-do-this-if-not-do-this.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

If the result of the database exists, do this, if not, do this

advertisements

I am checking a database to see if there is a data match. If there is, output some HTML, if not, output different HTML.

For some reason, this query is not working. The data in the database does provide a match, but the first HTML is not being output.

I have a feeling it has something to do with me using 'FALSE'... should I be doing this differently?

<?php

// Check current favourite status
$sql = "SELECT * FROM tbl_favourites WHERE user_id = :who AND favourite_id = :usernum AND favourite_active = '1' LIMIT 1";

$q   = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':usernum',$usernum,PDO::PARAM_INT);
$q->execute();

if($r = $q->fetch(PDO::FETCH_ASSOC)!== false)
{
    echo "<div id=\"favourite\" class=\"favouriteOptionActive\" onclick=\"loadXMLDoc('indexFavourite')\">Selected as favourite</div>";
}
else
{
    echo "<div id=\"favourite\" class=\"favouriteOption\" onclick=\"loadXMLDoc('indexFavourite')\">Add me as a favourite</div>";
}

?>


Instead of doing SELECT * do SELECT COUNT(*) since you aren't actually using any of the data queried.

$sql = "SELECT COUNT(*) FROM tbl_favourites WHERE user_id = :who AND favourite_id = :usernum AND favourite_active = '1' LIMIT 1";
$q   = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':usernum',$usernum,PDO::PARAM_INT);
$q->execute();
$found = $q->fetchColumn();

if ($found > 0) {
    // Do stuff
}
else {
    // Do other stuff
}

Also note that your comment the default way of PDO to manage errors is quite the same as or die() so no need for that is false. The default way PDO handles errors is silently. If you want either of the other two error modes, you need to set them yourself.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK