简体   繁体   中英

PHP: MYSQLI - Get data from same row

I have taken to this data that are the same but presented only one here

now I want to get text from last row

$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1'"); 
if($sql_query->num_rows > 0) {
    while ($fetch_data = $sql_query->fetch_array(MYSQLI_ASSOC)) {
        if($fetch_data["sent_by"] == 1) {
            echo $fetch_data["sent_to"]. " TEXT: ". $fetch_data["text"].  </br>";
        } else {
            echo $fetch_data["sent_by"]. " TEXT: ". $fetch_data["text"].  </br>";
        }
    }
}

Database structure:

在这里检查图像

Sorry for my bad english

UPDATED

If you have field id as auto increment field, then you can get the last row with this SQL query:

SELECT DISTINCT `sent_by`, `sent_to`, `id`, `text` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1' ORDER BY `id` DESC LIMIT 1

So change this:

$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1'"); 

on this:

$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to`, `id`, `text` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1' ORDER BY `id` DESC LIMIT 1"); 

In this new query you sort all results by the value of id field in descending order.

If you will remove DISTINCT from your query, you can remove also id from SELECT list in your query.

删除DISTINCT,并仅创建查询

$sql_query = $connection->query("SELECT sent_by, sent_to FROM chat WHERE sent_by = '1' OR `sent_to` = '1'"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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