【问题标题】:MySQL Returns PHP Associative Array - but I Can't Access Array DataMySQL 返回 PHP 关联数组 - 但我无法访问数组数据
【发布时间】:2013-10-21 14:28:53
【问题描述】:

我在 MySQL 表中有两条记录。我正在尝试使用SELECT COUNT(*) AS total FROM tableA,但没有得到我期望的结果。

下面的代码会回显Array ( [0] => Array ( [cnt] => 2 ) ):

// Count the amount of records in the table
$total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );

echo "Total Records:" . print_r( $total );

下面的代码没有回应:

// Count the amount of records in the table
$total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );

echo "Total Records:" . $total[0]['total'];

我怎样才能简化这个?我究竟做错了什么?我正在为此绞尽脑汁,但我无法让它发挥作用。

【问题讨论】:

    标签: php mysql arrays wordpress associative-array


    【解决方案1】:

    试试这个

    $total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );
    
    echo "Total Records:" . $total[0]['cnt'];
    

    谢谢。

    【讨论】:

    • 不一样,我用的是$total[0]['cnt']而不是你的$total[0]['total']
    【解决方案2】:

    试试这个:

    <?php
    
    $numRows = $wpdb->get_var( "SELECT COUNT( * ) AS total FROM tableA");
    
    echo $numRows;
    
    ?>
    

    【讨论】:

    • 感谢您的回复,但恐怕这并不能解决问题 - 它仍然返回空白/空。
    • 首先检查查询是否正常。如果是,那么尝试另一个 wordpress 函数来执行它。我认为查询是完美的。你检查过吗???
    • 是的,我有,这是我的错误 - 我在更改函数时没有取出 , ARRAY_A 参数,我尝试了它并且它有效!谢谢!
    • 欢迎......!始终注意您从其他地方粘贴的代码....享受........
    【解决方案3】:

    试试这个:

    $sql = "SELECT COUNT( * ) AS total FROM tableA";
    $sth = $DC->prepare($sql);
    $sth->execute();
    $result = $sth->fetch(PDO::FETCH_ASSOC);                
    echo $result['total'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      相关资源
      最近更新 更多