douzhang5984 2017-04-26 08:22
浏览 106
已采纳

如果value为empty / null,则根据数据库的长度替换数据库中的值

Scenario:

Database Table 
Column     Type      Length            Sample Values
emp_code   varchar     4            0011      0021    0012
emp_desc   varchar     2            01        03      01
emp_stat   varchar     1            1                 0

Problem:

I am querying so that I can write the result into a text file.

$file = "data.txt";
$f = fopen($file, "a");
$qry = "SELECT * FROM tbl_emp";
$result = mysqli_query($conn, $qry );
if(!$result) {
    echo "Cannot do query" . "<br/>";
exit;
}

$num_results =mysqli_num_rows($result);
for ($i=0; $i<=$num_results; $i++) {
    $row = mysqli_fetch_assoc ($result);
        $emp_code = (empty($row['emp_code']) ? "    " : $row['emp_code']); //replace with 4 spaces
        $emp_desc = (empty($row['emp_desc']) ? "  " : $row['emp_desc ']);  //replace with 2 spaces
        $emp_stat = (empty($row['emp_code']) ? " " : $row['emp_code']);  //replace with 1 space

     $data = "$emp_code $emp_desc $emp_stat
";
     fwrite($f,$data); 
}

Data.Txt should contain:

0011011
002103 
0012010

But this is the result:

0011011
002103 
001201

If the value of the row is 0, it replaces it with blank when it shouldn't. What needs to be changed to get the correct data? TIA.

  • 写回答

1条回答 默认 最新

  • douqingzhi0980 2017-04-26 08:30
    关注

    Don't use empty. 0 is empty. Depending on what you are checking there it can be one of:

    $emp_stat = (is_null($row[...]) ? " " : $row[...])
    $emp_stat = (($row[...] === "") ? " " : $row[...])
    $emp_stat = (is_numeric($row[...])? $row[...] : " ")
    

    etc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度