gpt4 book ai didi

php - Echo DISTINCT 行以从 MYSQL 中删除重复结果

转载 作者:行者123 更新时间:2023-11-29 12:23:19 25 4
gpt4 key购买 nike

我有以下代码,效果很好:

///////////////////////
$todo=$_POST['todo'];
if(isset($todo) and $todo=="search"){
$species=$_POST['species'];
$lab_section=$_POST['lab_section'];
$search_text=$_POST['search_text'];
$type=$_POST['type'];

$query="select * from mytable where ";

if(strlen($species) > 0 ){
$query.= " species='$species' and ";
}
if(strlen($lab_section) > 0 ){
$query.= " lab_section='$lab_section' and ";
}

////////////////////////// Key word search query /////////
$search_text=ltrim($search_text);
$search_text=rtrim($search_text);

if(strlen($search_text)>0){
if($type<>"any"){
$query .=" name='$search_text'";
}else{
$kt=split(" ",$search_text);//Breaking the string to array of words
// Now let us generate the sql
while(list($key,$val)=each($kt)){
if($val<>" " and strlen($val) > 0){$query .= " lab_section like '%$val%' or name like '%$val%' or species like '%$val%' or ";}
}
$query=substr($query,0,(strLen($query)-3));
// this will remove the last or from the string.
} // end of if else based on type value
$query.=" and ";
}// end of if area , if search_text value is entered

$query=substr($query,0,(strLen($query)-4));

echo "<div class='search-separator'></div>";
// Display records ////
foreach ($dbo->query($query) as $t) {
echo "$t[name],$t[lab_section],$t[price],$t[species]"; }
}
?>

但是 MYSQL 的行几乎是重复的。但它们都有独特的名字。所以我需要按名称删除重复的结果。换句话说,我只想按结果的唯一名称列出结果。如何通过唯一名称删除重复结果?

我认为我可以做到,例如通过以下方式:

select DISTINCT ...... 
from mytable
group by name

但我不知道把它放在上面的代码中的哪里......

最佳答案

在行中输入 DISTINCT

$query="select * from mytable where  ";

您可以在行后使用 GROUP

$query=substr($query,0,(strLen($query)-4));

但是一般来说,代码并不好。不要在查询中使用直接从用户传递的值($_GET、$_POST 等)。至少使用 sprintf(),但最好使用占位符。

为什么不能替换这两行: $search_text=ltrim($search_text); $search_text=rtrim($search_text);与$search_text=trim($search_text);

您不需要行 $query=substr($query,0,(strLen($query)-4)); 例如,您可以将所有这些查询部分写入数组,然后使内爆('AND',$条件);就在“一会儿”之后

关于php - Echo DISTINCT 行以从 MYSQL 中删除重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com