简体   繁体   English

回显MySQL查询的单个结果

[英]Echo a single result from MySQL query

I have the following MySQL query; 我有以下MySQL查询;

    SELECT *, @rownum := @rownum + 1 from
    (
    SELECT (display_name) 'Author',
        IFNULL(ROUND(SUM(balance.meta_value),2),2) 'Balance'
    FROM posts p
    JOIN users u 
        ON p.post_author = u.ID
    JOIN postmeta odd ON p.ID = odd.post_id AND odd.meta_key = 'odd' AND odd.meta_value >= 1.5
    LEFT JOIN postmeta balance 
        ON p.ID = balance.post_id AND balance.meta_key = 'balance'
    WHERE p.post_status = 'publish' and p.post_author = 'User1' 
    GROUP BY u.ID
    ORDER BY Balance DESC
    )x, (SELECT @rownum := 0) r

which produces the following table; 产生下表;

 Users      Balance       @rownum := 0       @rownum := @rownum + 1
 User1      5.88              0               1
 User2      -23.41            0               2

How can I echo the value of the last column for the first user (where [@rownum := @rownum + 1] = 1. 如何回显第一个用户的最后一列的值(其中[@rownum:= @rownum + 1] = 1。

Thanks 谢谢

$result = mysql_query("your's sql query");
$row = mysql_fetch_array($result);
echo $row[2];

This is code for your specific question. 这是您特定问题的代码。 Read more about here . 了解更多关于这里 Whole extension is deprecated so for your homework read this and rewrite my code. 不推荐使用整个扩展名,因此您的作业请阅读此内容并重写我的代码。

You need to use the mysqli_* functions in php to connect and execute the query. 您需要使用php中的mysqli_ *函数来连接和执行查询。 Once the query is executed you retrieve the first row and then echo the 3rd column. 执行查询后,检索第一行,然后回显第3列。

Something like this should work (Change the mysql params to valid user/name passwords for your host): 这样的东西应该工作(将mysql参数更改为主机的有效用户/名称密码):

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT *, @rownum := @rownum + 1 from
    (
    SELECT (display_name) 'Author',
        IFNULL(ROUND(SUM(balance.meta_value),2),2) 'Balance'
    FROM posts p
    JOIN users u 
        ON p.post_author = u.ID
    JOIN postmeta odd ON p.ID = odd.post_id AND odd.meta_key = 'odd' AND odd.meta_value >= 1.5
    LEFT JOIN postmeta balance 
        ON p.ID = balance.post_id AND balance.meta_key = 'balance'
    WHERE p.post_status = 'publish' and p.post_author = 'User1' 
    GROUP BY u.ID
    ORDER BY Balance DESC
    )x, (SELECT @rownum := 0) r";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    $row = $result->fetch_row(); // Fetch the first row
    echo $row[2]; // Print the 3rd column

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM