0

I want to be able to have control of what I print in this array. So far this is what I have:

<?php
/* DB CONNECTION */
try {
  $pdo = new PDO('mysql:host=' . DB_HOST . '; dbname=' . DB_NAME . '', DB_USER, DB_PASSWORD);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
  $sql = 'SELECT nombre,categoria,descripcion FROM equipos ORDER BY nombre ASC';
  $result = $pdo->query($sql);
}
catch(PDOException $e) {
  echo $error = 'Error fetching jokes: ' . $e->getMessage();
  exit();
}

/*FETCH ARRAY */
$equipos = array();
while ($row = $result->fetch()) {
  $equipos[] = $row['nombre'];
  $equipos[] = $row['categoria'];
  $equipos[] = $row['descripcion'];
}
?>       
<?php
/* PRINT ARRAY */
foreach($equipos as $equipo): ?>
  <p><?php
  echo htmlspecialchars($equipo);
?></p>
<?php
endforeach; 
?>

My results are:

Value1
value2
Value3

etc.

I want to be able to print something like:

Value1, Value2, Value3
Value4, Value5, Value6

There's must be a practical easier way.

4

2 回答 2

0

很难说你想要什么,但我在黑暗中拍摄
注意连接到 PDO的正确方法

<?php

$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$dsn = 'mysql:host=' . DB_HOST . '; dbname=' . DB_NAME . ';charset=utf8';
$pdo = new PDO($dsn, DB_USER, DB_PASSWORD, $opt);

$sql    = 'SELECT nombre,categoria,descripcion FROM equipos ORDER BY nombre ASC';
$result = $pdo->query($sql);
$data   = $result->fetchAll();
?>       

现在在$data变量中,您有一个包含所有行的数组,每行都包含一个带有选定字段的数组。因此,您可以通过字段名称控制它们:

<?php foreach($data as $row): ?>
  <p>
    <?=htmlspecialchars($row['nombre'])?>,
    <?=htmlspecialchars($row['categoria'])?>,
    <?=htmlspecialchars($row['descripcion'])?>
  </p>
<?php endforeach ?>
于 2013-04-10T16:31:37.503 回答
-1

而不是使用 foreach 语句使用

for(var i = 0;i<(sizeof($equipos);i++)
{
 echo htmlspecialchars($equipo[i]);
}
于 2013-04-10T16:21:16.793 回答