各列名を知らなくても、すべての行のすべての列を取得する場合は、テーブルの列数を数えることができます。
$queryCols = "SHOW COLUMNS FROM players":
$queryPlayers = "SELECT * FROM players";
$result = mysql_query($queryPlayers);
$playerColumns = mysql_query($queryCols);
$colsResult = mysql_fetch_row($playerCols);
$numFields = count($colsResult);
while ($row = mysql_fetch_array($result)) {
for ($i = 0; $i < $numFields; $i++) {
$row[$i]; // Each column in each row
}
}
これは、間もなく廃止されるmysqli
後継となるselectステートメントの例です。 mysql_* statements
$DB_NAME = 'test';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf('Connection to $s using %s@$s failed: %s\n',
$DB_NAME, $DB_USER, $DB_HOST, mysqli_connect_error());
exit();
}
$query = "SELECT `fname`, `lname`, `team` FROM `players`;";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($fname, $lname, $team);
$table = <<< TABLE
<table border="1">
<thead><tr>
<th>First Name</th><th>Last Name</th><th>Team</th>
</tr></thead>
<tbody>
TABLE;
while ($stmt->fetch()) {
$table .= "<tr><td>$fname</td><td>$lname</td><td>$team</td></tr>";
}
$table .= "</tbody></table>";
printf($table);
$stmt->close();
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
テーブル
CREATE TABLE IF NOT EXISTS `players` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`fname` varchar(32) NOT NULL,
`lname` varchar(32) NOT NULL,
`team` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
INSERT INTO `players` (`id`, `fname`, `lname`, `team`) VALUES
(1, 'Peyton', 'Manning', 'Denver Broncos'),
(2, 'Matt', 'Ryan', 'Atlanta Falcons'),
(3, 'Tom', 'Brady', 'New England Patriots'),
(4, 'Colin', 'Kaepernick', 'San Francisco 49ers'),
(5, 'Matt', 'Schaub', 'Houston Texans'),
(6, 'Aaron', 'Rodgers', 'Green Bay Packers'),
(7, 'Joe', 'Flacco', 'Baltimore Ravens'),
(8, 'Robert', 'Griffin III', 'Washington Redskins'),
(9, 'Andrew', 'Luck', 'Indianapolis Colts'),
(10, 'Matt', 'Flynn', 'Seattle Seahawks'),
(11, 'Andy', 'Dalton', 'Cincinnati Bengals'),
(12, 'Christian', 'Ponder', 'Minnesota Vikings');
結果:
First Name Last Name Team
Peyton Manning Denver Broncos
Matt Ryan Atlanta Falcons
Tom Brady New England Patriots
Colin Kaepernick San Francisco 49ers
Matt Schaub Houston Texans
Aaron Rodgers Green Bay Packers
Joe Flacco Baltimore Ravens
Robert Griffin III Washington Redskins
Andrew Luck Indianapolis Colts
Matt Flynn Seattle Seahawks
Andy Dalton Cincinnati Bengals
Christian Ponder Minnesota Vikings