错误警告:join():PHP中传递了无效的参数

时间:2019-03-27 07:58:48

标签: php mysql arrays join pdo

请帮助, 我收到错误消息“警告:join():在...上在线传递了无效的参数”。

这是我的代码:

$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC"; 

$stmt = $DB_con->prepare($query);

$stmt->execute();   

$kategori = array();

if($stmt->rowCount()>0) {                       
    while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    $kategori = print($row['kategori']);    
}
}else{
 echo "Nothing here...";                
}

join($kategori, ',');

我希望输出:数据,数据,数据,数据,书,书 但实际输出是“ DataDataDataDataBookBook”和错误“警告:join():在...上在线传递了无效的参数...”

2 个答案:

答案 0 :(得分:2)

只需在每次迭代中附加$row['kategori']并在join()implode()调用中更改参数的顺序即可:

<?php

// Get data
$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC"; 
$stmt = $DB_con->prepare($query);
$stmt->execute();   

// Fetch data    
$kategori = array();
if ($stmt->rowCount() > 0) {                       
   while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
       $kategori[] = $row['kategori'];    
   }
} else {
    echo "Nothing here...";                
}

// Output
echo implode(',', $kategori);

?>

答案 1 :(得分:1)

获取一堆记录然后将它们连接在一起的另一种方法是在mysql中使用Java Web Start Technology为您完成工作。另外,由于您没有绑定任何东西-您可以调用query()。然后,您将从数据库中获得包含内容的第一行-因此,最后一位是说它是否为空,然后将值设置为Nothing here...(使用?:完成) ...

$query = "SELECT GROUP_CONCAT(`kategori`) as kategori 
             FROM `table` 
             ORDER BY `id` DESC"; 

$stmt = $DB_con->query($query);
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$output = $row['kategori']?:"Nothing here...";
echo $output;

如果您仍然需要单独的数据行,那么另一种替代方法是使用PDO::FETCH_COLUMNfetchAll()返回结果,然后像其他解决方案一样使用implode()

$query = "SELECT `kategori` 
             FROM `table` 
             ORDER BY `id` DESC"; 

$stmt = $DB_con->query($query);
$kategori=$stmt->fetchAll(PDO::FETCH_COLUMN);
echo implode(',', $kategori)?:"Nothing here...";