简体   繁体   中英

PHP - how to select from a table one query

I got a table that contains ID, Names, message, and time , I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code

$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}

That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?

Thanks,
Klaus

If you want only one message you can use LIMIT like this

SELECT * FROM table ORDER BY time LIMIT 1

Or if you want only one message from some id then you can use GROUP BY

SELECT * FROM table ORDER BY time GROUP BY id

Sure, pretty straightforward

This will fetch all messages given ID:

$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());

while($arr = mysql_fetch_array($query)){
    $num = mysql_num_rows($query);
    $msg = $arr['message'];
    echo $msg;
}

and this will fetch only the first message given ID

$id = 10 
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());

$row = mysql_fetch_array($query));
if($row){
    $msg = $row['message'];
    echo $msg;
}else{
    echo 'no messages for id '.$id;
}

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