Вопрос

i have a blogging CMS and in the DB each of the blogs has up to 10 tags. These tags are stored simply as comma separated values for each of the rows.

I want to select every single row, and then get every fields data and then put it into one string.

So e.g:

$query = "SELECT * FROM blogs"; 
$query_params = array(); 
try{ 
  $stmt = $db->prepare($query); 
  $result = $stmt->execute($query_params); 
  $row = $stmt->fetch();
  $tags = $row['tags'];
} 
catch(PDOException $ex) 
{ 
  die(); 
} 

echo $tags;

This was just a test, but it obviously just puts the first row into the $tags variable. How can i put every rows table field of 'tags' into one array?

Thanks!

Craig.

Это было полезно?

Решение

You need to read all the rows in a loop, and concatenate them onto the variable.

$query = "SELECT * FROM blogs"; 
$query_params = array(); 
$tags = '';
try{ 
  $stmt = $db->prepare($query); 
  $result = $stmt->execute($query_params); 
  while ($row = $stmt->fetch()) {
    $tags .= $row['tags'];
  }
} 
catch(PDOException $ex) 
{ 
  die(); 
} 

echo $tags;

Другие советы

You can use a foreach loop and fetchAll, like so:

$rows = $stmt->fetchAll();
foreach ($rows as $row) {
    $tags[] = $row['tags'];
}

$oneHugeString = implode(",", $tags);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC));
$result = "";
foreach($rows as $row) {
   $result .= $row['tags'] . ", ";
}

(Or whatever string formatting you want).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top