【问题标题】:How to get the maximum value of a column of a MySQL table, in PHP land, using the WordPress API如何使用 WordPress API 在 PHP 中获取 MySQL 表的列的最大值
【发布时间】:2015-12-30 23:23:26
【问题描述】:

这让我很头疼。在 PHP 领域中,我只需要来自名为 work_carousels 的表中的最大值 id。运行

SELECT MAX(id) FROM work_carousels

直接从 phpMyAdmin 中的命令行返回

   MAX(id)
   -------
     12

我所需要的只是我的 PHP 中的那个数字 12(或目前发生的任何数字)! WordPress API for interacting with the database 告诉我我应该使用

$wpdb->get_results

获取查询结果对应的PHP对象。我试过了

$resultObj = ($wpdb->get_results('SELECT MAX(id) FROM work_carousels'));
$lastAddedCarouselId = $resultObj->MAX(id);  

这不起作用,导致内部服务器错误。我也试过了

$lastAddedCarouselId = ($wpdb->get_results('SELECT MAX(id) FROM work_carousels'));

那没有用。还有其他想法吗?

【问题讨论】:

  • $resultObj->MAX(id); 将尝试在$resultObj 上调用函数MAX。而是尝试将其别名为查询中的可用名称:SELECT MAX(id) as max_id FROM work_carousels,然后您可以使用$resultObj->max_id 访问它
  • 由于我不知道 $wpdb->get_results() 的实际工作原理,我只是猜测这会完成这项工作(因此它不是答案)

标签: php mysql wordpress wordpress-theming


【解决方案1】:

这应该可行:

SELECT id FROM work_carousels ORDER BY id DESC LIMIT 1;

【讨论】:

    【解决方案2】:

    对我来说,这段代码有效

    <?php
    $max_id = $wpdb->get_var( 'SELECT MAX(id) FROM ' . $wpdb->prefix . 'work_carousels' );
    

    更多关于$wpdb-&gt;get_var()这里https://developer.wordpress.org/reference/classes/wpdb/get_var/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2016-04-14
      • 2010-12-06
      • 2018-10-14
      • 2017-05-24
      相关资源
      最近更新 更多