Search code examples
phpmysqlshow-hide

Hiding text/links with 0 value results by php


I have a list of links in my html table, like: Bra: 5psc, Brasets: 15pcs, Blanket: 0pcs, Towel: 0pcs. I need that "Blanket" and "Towel" and other list positions" with 0 value hiding from list until they 0 value, after value change to more than 0pcs (for example: 1pcs or more) they would shown. "Blanket: 0pcs" and "Towel: 0pcs" and "other goods" with 0pcs value not hiding but still show 0pcs value. What i'm doing wrong or what my mistake? Maybe there is another way to do this. I can't understand. Thank you for help.

<?
  $resultonshafa = mysql_query("SELECT count(customers_id) from tbl_customers WHERE shafa='Y'");
  $resultonshafasaled = mysql_query("SELECT count(customers_id) from tbl_customers WHERE shafa='Y' and saled='Y'");
  $resultonolx = mysql_query("SELECT count(customers_id) from tbl_customers WHERE last_name='Y'");
  $resultonolxsaled = mysql_query("SELECT count(customers_id) from tbl_customers WHERE last_name='Y' and saled='Y'");

  $topmenuOnShafa = mysql_result($resultonshafa, 0);
  $topmenuNotOnShafa = mysql_result($resultonshafasaled, 0);
  $topmenuOnOlx = mysql_result($resultonolx, 0);
  $topmenuNotOnOlx = mysql_result($resultonolxsaled, 0);

  $topmenuOnOlxText = "Blanket : ";
  $topmenuOnShafaText = "Towel : ";
 ?>

<?php if ($topmenuNotOnOlx!=0): ?>
<span class="saled-warning"><a href="some_link" target="_self"><?=$topmenuNotOnOlx;?></a></span>
<?php endif; ?>
<?php if ($topmenuOnOlx!=0): ?><?=$topmenuOnOlxText;?><?php endif; ?>
<?php if ($topmenuOnOlx!=0): ?>
<a href="some_link" target="_self"><?=$topmenuOnOlx;?></a>
<?php endif; ?>

<?php if ($topmenuNotOnShafa!=0): ?>
<span class="saled-warning"><a href="some_link" target="_self">
<?=$topmenuNotOnShafa;?></a></span>
<?php endif; ?>

Solution

  • You could just run a single query to get all of that information:

    SELECT
       SUM(shafa='Y') AS only_shafa,
       SUM(shafa='Y' AND saled='Y') as saled_and_shafa,
       SUM(last_name='Y') AS only_lastname,
       SUM(last_name='y' AND saled='Y') AS saled_and_lastname
    FROM ...
    

    MySQL will auto-convert the boolean true/false returned by those =/and tests into integers, and add them up. Then you only run this ONE query, fetch a single row of results:

    $res = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_assoc($res);
    

    And then test for those values with $row['only_salend'] and the like.

    But note that your code simply assumes queries never fail. That is a BAD assumption. if the query fails, you get boolean FALSE returned. You would then try to get a result from that false, causing ANOTHER false. And since your results are now boolean FALSE, false != 0 will evaluate to (falsely) evaluate to boolean TRUE.