简体   繁体   English

php sql如何仅显示行中的最后一个值?

[英]php sql How to display only the last value in the row?

I need only to display the last values in the row. 我只需要显示行中的最后一个值。 Now its displaying 现在显示

Message for: Rocha : gff Message for: Rocha : Message for: Rocha : hi my name is kenny 消息:Rocha:gff消息:Rocha:消息:Rocha:嗨,我叫肯尼

I only need it to display Message for: Rocha : hi my name is kenny. 我只需要显示以下消息即可:Rocha:嗨,我叫肯尼。 Thank you 谢谢

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, className, lastname, messages FROM Mymesages";
$result = $conn->query($sql);

if ($result->num_rows > 0) {


    // output data of each row
    while($row = $result->fetch_assoc()) {      


        if("CPS210-CompSci-I (4)"==$row["className"] && $lastname== $row["lastname"]){
          echo  "Message for: "   . $row["lastname"]. " : " .  $row["messages"]. "<br>";
        }

    }

}

$conn->close();
?>

If you want to display the last row, then your query should be like this: 如果要显示最后一行,则查询应如下所示:

$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";

And later, instead of while loop simply fetch the row like this: 然后,代替while循环,只是像这样获取行:

$row = $result->fetch_assoc();

If you're looking for only one record, that too the last one, you just need to modify your query a little. 如果只查找一条​​记录,也只查找最后一条,则只需要稍微修改一下查询即可。 Also, there's no need for the loop in that case. 同样,在这种情况下也不需要循环。

$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";

Replace this line: 替换此行:

while($row = $result->fetch_assoc()) {      

With simply: 简单地:

$row = $result->fetch_assoc();

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

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