douyun3887 2014-03-24 01:11
浏览 141
已采纳

在mySQL查询中使用MAX()会产生有问题的结果

I'm trying to make multiple queries in order to find the most recent entry in a database by username.
Here's my code:

<?php  
    require_once("../includes/db_connection.php");  

    $userID = $_POST["userID"];
    $returnString = array();

    // Query the max id value of a given key_id (find the most recent upload)
    $query = "SELECT MAX(id) FROM photos WHERE key_id = {$userID}";
    $result = mysqli_query($connection, $query);
    //additional while loop could go here

    //now get the url where from the max id value that we just queried
    $query = "SELECT url FROM photos WHERE id = {$urlID}";
    $result = mysqli_query($connection, $query);

    $returnString['url'] = $urlID;

    mysqli_free_result($result);        
    echo json_encode($returnString);


?>

I think the problem lies in the first query. When I return the result from that, I get:

{"maxID": "current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

When I create a while loop to capture the array (why I need to do this is beyond me because it will only ever return 1 value):

while($row = mysqli_fetch_assoc($result)) {$returnString[] = $row;} 

Then I get this funky result:

[{"MAX(id)":"30"}] 

30 is the correct value, but then I don't know how to use that result in my next mySQL query.

**********UPDATE*************

The query :

SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID});

Works perfectly when making the query from within mySQL, but doesn't work from my php script. It returns this weird string:

{"url":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}} 

Here's the updated script:

require_once("../includes/db_connection.php");  

$userID = $_POST["userID"];
$returnString = array();

$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);

mysqli_free_result($result);    

$returnString['url'] = $result; 
echo json_encode($returnString);
  • 写回答

3条回答 默认 最新

  • duanchen7703 2014-03-24 01:28
    关注

    Updated answer:

    $query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
    $result = mysqli_query($connection, $query);
    $row = mysqli_fetch_array($result):
    $url = $row['url'];
    echo json_encode($url);
    mysqli_free_result($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路