Tsvetomirov Yordan
Tsvetomirov Yordan

Reputation: 77

Can we make database return something else,different from 0 when the field in empty

So my whole question in in the Title,but lets make it easier for you guys to understand.Now when there is an empty field in database php returns "0"There is an example:example one

I need when there is an empty spot this to be displayed,and by this i mean the "-" or "~" sign.

example two

So is there way to make that automatic with PHP,when field is empty instead of "0" any symbol to be displayed,and if there is pleasee tell me <3 There is my Code:

<!--------------------------------------------------------------------------
                                  PHP CODE
--------------------------------------------------------------------------->
<?php
$page_id= $_GET['id'];

$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";

$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$connect->set_charset("utf8");
$query = "SELECT * FROM food_data_bg where id = '" . $page_id . "'";
$result = mysqli_query($connect, $query);
?>
<?php while($row1 = mysqli_fetch_assoc($result)):; ?>

<?php
if (mysqli_num_rows($result) == 0){
echo "daaaaa";
}
$title= $row1['title'];
$fimage = $row1['fimage'];
$state = $row1['state'];
$carbs = $row1['carbohydrates'];
$proteins = $row1['proteins'];
$fats = $row1['fats'];
$caloriesTotal = $row1['calories total'];
$carbsCalories = $row1['carbs cal'];
$protCalories = $row1['prot cal'];
//and so on ...
//and after the all variables i am just displaying results in html elements like so
?>
<!--------------------------------------------------------------------------
                               HTML EXAMPLE
--------------------------------------------------------------------------->
<div class="food-macros"><b>Общи Калории</b><span><?php echo $caloriesTotal; ?></span></div>
<div class="food-macros"><b>Протеин</b><span><?php echo $proteins ?></span></div>
<div class="food-macros"><b>Въглехидрат</b><span><?php echo $carbs; ?></span></div>
<div class="food-macros"><b>Мазнини</b><span><?php echo $fats; ?></span></div>

Sorry if there is a mistake or something missing,i will fix and link everything you guys need to help me after get back from university,THANKS <3

Upvotes: 0

Views: 28

Answers (1)

Carlos Gonzalez
Carlos Gonzalez

Reputation: 374

for each item in your database you want to check if is ZERO (0):

$carbs = ($row1['carbohydrates'] === 0) ? "-" : $row1['carbohydrates'];
/// === means strictly same value

and so on...

EDIT:

function zeroField($field, $replace = "-")
{
    return ($field === 0) ? $replace : $field;
}

usage:

$carbs = zeroField($row1['carbohydrates']); //output: "-" or field value

//or change sign
$carbs = zeroField($row1['carbohydrates'],"~"); //output: "~" or field value

Upvotes: 2

Related Questions