【问题标题】:How to access stdClass variables stdClass Object([max(id)])=>64)如何访问 stdClass 变量 stdClass Object([max(id)])=>64)
【发布时间】:2010-06-12 15:17:54
【问题描述】:

我需要数据库表中最后一个有效条目,它是具有最大主键的行。所以使用 mysqli,我的查询是“SELECT MAX(id) FROM table LIMIT 1”。此查询返回正确的数字(使用 print_r()),但我不知道如何访问它。这是主要代码。请注意,$this->link 指的是具有 mysqli 连接的类。

$q="select max(id) from stones limit 1";
    $qed=$this->link->query($q) or die(mysqli_error());
    if($qed){
        $row=$qed->fetch_object();
        print_r($row);
        echo $lastid=$row;//here is the problem
    }

有效行 print_r($row) 回显“stdClass Object ( [max(id)] => 68 )”

【问题讨论】:

    标签: php mysql mysqli stdclass


    【解决方案1】:

    您需要命名聚合结果。

    SELECT MAX(id) AS maxid FROM stones
    

    然后你可以访问像$row->maxid这样的值。

    【讨论】:

    • 谢谢你的作品。我找到了一个不太干净的解决方案,那就是使用 fetch_array() 而不是 fetch_object。但是,我会试试你的。
    【解决方案2】:

    你试过了吗:

    $row->max(id)? 或者 $lastid=$row["max(id)"];

    您可能需要选择 max(id) as "MaxID" 和 $lastid=$row->MaxID;

    【讨论】:

      【解决方案3】:

      我需要数据库表中最后一个有效条目,它是具有最大主键的行。

      您说您想要最后一个条目,但您只是获取 ID。大概您打算使用它通过第二个查询来获取整行。

      相反,您可以在一个查询中完成整个操作:

      SELECT *
      FROM stones
      ORDER BY id DESC
      LIMIT 1
      

      【讨论】:

      • 感谢回复,我只想要id
      猜你喜欢
      • 2015-09-22
      • 2012-03-10
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多