[英]Coordinates from MySQL to HTML table (PHP, PDO, MySQL)
I am creating game which uses MySQL database to create "playing field". 我正在创建使用MySQL数据库创建“运动场”的游戏。
In my MySQL table I have two columns pointX
and pointY
, both INT
. 在我的MySQL表中,我有两列pointX
和pointY
,均为INT
。 I could also use POINT
, but in my case these two columns are better solution. 我也可以使用POINT
,但对我而言,这两列是更好的解决方案。
| id | pointX | pointY | player | game |
|----|--------|--------|--------|------|
| 1 | -2 | 1 | 7 | 10 |
| 2 | -3 | 2 | 5 | 10 |
| 3 | 2 | -2 | 2 | 10 |
| 4 | -2 | -1 | 1 | 10 |
I should produce HTML table from this MySQL table. 我应该从该MySQL表生成HTML表。 Something like this, but with no coordinateheaders (below those are only for easier understanding): 这样的事情,但是没有坐标头(下面只是为了更容易理解):
|-----|----|----|----|----|----|----|
| Y/X | -3 | -2 | -1 | 0 | 1 | 2 |
|-----|----|----|----|----|----|----|
| -2 | | | | | | 2 |
|-----|----|----|----|----|----|----|
| -1 | | 1 | | | | |
|-----|----|----|----|----|----|----|
| 0 | | | | | | |
|-----|----|----|----|----|----|----|
| 1 | | 7 | | | | |
|-----|----|----|----|----|----|----|
| 2 | 5 | | | | | |
|-----|----|----|----|----|----|----|
Plus.. every <td>
should have attribute data-cell
, which includes coordinates, as example data-cell="-2x-1"
. 另外,每个<td>
应该具有属性data-cell
,其中包括坐标,例如data-cell="-2x-1"
。
What is the best way to get started? 最好的入门方法是什么?
$rng = $dbh->prepare('
SELECT MIN(pointX) AS minX, MIN(pointY) AS minY,
MAX(pointX) AS maxX, MAX(pointY) AS maxY
FROM field
WHERE game = ?
LOCK IN SHARE MODE
');
$qry = $dbh->prepare('
SELECT pointX, pointY, player
FROM field
WHERE game = ?
ORDER BY pointX, pointY
');
$dbh->beginTransaction();
$rng->execute([$game_id]);
$qry->execute([$game_id]);
$dbh->rollBack();
$limits = $rng->fetch();
$player = $qry->fetch();
echo '<table>';
for ($y = $limits['minY']; $y <= $limits['maxY']; $y++) {
echo '<tr>';
for ($x = $limits['minX']; $x <= $limits['maxX']; $x++) {
printf('<td data-cell="%dx%+dy">', $x, $y);
if ($player and $player['pointX'] == $x and $player['pointY'] == $y) {
echo htmlentities($player['player']);
$player = $qry->fetch();
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
It looks like you are already off to a good start. 看来您已经有了一个良好的开端。 Assuming the number of cells for X and Y as $xcells and $ycells, the next step I would take is to build your table like so: 假设X和Y的像元数分别为$ xcells和$ ycells,我下一步将要像这样构建表:
echo "<table>";
for ($i = -3; $i < $ycells; i++) {
echo "<tr>";
for ($j = -3; $j < $xcells; j++) {
echo "<td data-cell='" . $i . "y" . $j . "x'>";
}
echo "</tr>";
}
echo "</table>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.