我们是否可以使数据库返回其他内容,当空字段为

时间:2017-03-18 15:31:09

标签: php sql

所以我在标题中的整个问题,但让我们让你们更容易理解。现在当数据库中有一个空字段时,php返回“0”有一个例子:example one

当需要显示空白点时我需要显示,这是指“ - ”或“〜”符号。

example two

有没有办法用PHP自动生成,当字段为空而不是“0”时,任何符号都要显示,如果有请告诉我< 3 有我的代码:

<!--------------------------------------------------------------------------
                                  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>

对不起,如果有错误或缺少某些东西,我会修复并链接你们从大学回来后需要帮助我的一切,谢谢&lt; 3

1 个答案:

答案 0 :(得分:2)

对于数据库中要检查的每个项目是否为零(0):

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

依旧......

编辑:

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

用法:

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

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