我试图在php中找到一个方法,将所有相关的搜索返回结果从mysql DB连接成一个用逗号分隔的单个字符串。请参阅下面的DB表php输出格式和php代码。
海滩桌:
$sortBy
Beach_Act_Type表:
bname length city_name
Beach A 4 City Z
Beach B 3 City X
Beach C 7 City E
输出I' m寻找:
bname act_type
Beach A Swimming
Beach A Surfing
Beach B Surfing
Beach C Swimming
Beach C Fishing
Beach C Surfing
而不是这种输出格式:
`beach`.`bname` `beach_act_type`.`act_type`
Beach C Swimming, Fishing, Surfing
我的PHP代码:
`beach`.`bname` `beach_act_type`.`act_type`
Beach C Swimming
Beach C Fishing
Beach C Surfing
答案 0 :(得分:0)
您正在寻找的功能是GROUP_CONCAT
。
SELECT
`beach`.`bname`,
GROUP_CONCAT(`beach_act_types`.`act_type`) types
FROM
`beach`
INNER JOIN
`beach_act_types` ON
`beach`.`bname` = `beach_act_types`.`bname`
WHERE
`beach`.`bname` = '$search'
PS。应该警告您存在SQL注入,请考虑切换到准备好的语句。
答案 1 :(得分:-2)
你只是在捣乱两个单独的表数据,它们不会给你你想要的结果,请尝试下面的代码 你不能得到","在不同的表数据中。 试试这个,
<?php $conn = new
mysqli('localhost','test','','beachproject');
if (!$conn) { die('DB Connection
Error'); }
$search = $_POST['search'];
$search_sql="select `beach`.`bname`,
`beach_act_type`.`act_type` from
`beach` inner join `beach_act_types` on
`beach`.`bname`=`beach_act_type`.`
bname` where
`beach`.`bname`='$search'";
$search_query=$conn
>query($search_sql);
if ($search_query->num_rows > 0) {
while($row = $search_query
>fetch_assoc()) { echo "<table
border='1' cellpadding='4'>
<tr> <th>Beach Name</th> <th>Beach
Activity Allowed</th> </tr>"; echo "<tr>";
echo "<td>" . $row['bname'] . , .
$row['act_type']"</td>"; echo "</tr>";
echo "</table>"; } } else { echo "No
Search Results"; } ?>