doulin4844 2015-12-07 04:32
浏览 231
已采纳

仅当count为0时才返回false

I am trying to make sure that my function return false only if count for cc is 0. I keep getting false back from my function even when count is more than 0.

My function:

function db_cc_exists($link, $cc) {
  $sql = "SELECT count(*) as count FROM visitors WHERE cc = '$cc' LIMIT 1";
  $result = mysqli_query($link, $sql);
  $row = mysqli_fetch_array($result);
  $ret = $row[0];

  mysqli_free_result($result);
  return (intval($ret) == 0 ? FALSE : TRUE);
}

$link is the connection of my database.

  • 写回答

2条回答 默认 最新

  • douhe4608 2015-12-07 04:42
    关注

    $ret ($row[0]) is an array. Use $ret['count']

    return (intval($ret['count']) == 0 ? FALSE : TRUE);
    

    UPDATE

    I believe my original answer is actually incorrect.

    mysqli_fetch_array takes 2 parameters - the second is the type of array to return. The default is MYSQLI_BOTH which creates an array with both numeric indexes (in your case with element '0') and associative indexes (in your case 'count').

    $row[0]; should have returned the count.

    The options for the 2nd parameter

    /* numeric array */
    $row = mysqli_fetch_array($result, MYSQLI_NUM);
    
    /* associative array */
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    
    /* associative and numeric array */
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    

    If you followed my original answer and used intval($ret['count'], you should have received the error "Illegal string offset 'count'".

    A simple test is to put a var_dump($row) statement after it is set to see what is being returned.

    You should get something like:

    array(2) { [0]=> string(5) "123" ["count"]=> string(5) "123" } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目