我正在构建一个浏览器游戏,以便学习html,css,php和MySQL。我写了下面的代码,允许玩家建造新的建筑物。桌子加载所有建筑物,一切正常,甚至插入数据库。但是,由于我是新手,我遇到的问题是应该放入DB的所有值都是空的。 $ _SESSION [user_id]有效。但不是数组中的值。 所以我认为问题可能是我不知道如何正确地获得这些值。
所以,如果有人想在这里帮助我,我会非常感激和教育! :)
function buildings() {
global $database;
global $player;
global $self_link;
// Fetch buildings
$result = $database->query("SELECT * FROM buildings");
$buildings = array();
while($building = $database->fetch($result)) {
$buildings[$building['id']] = $building;
}
if(!empty($_POST['build'])) {
$building_id = (int)$_POST['building_id'];
$amount = $_POST['amount'];
try {
if($player->money < $buildings[$building_id]['cost']) {
throw new Exception("You do not have enough money to build this!");
}
// Purchase technique
$player->money -= $buildings[$building_id]['cost'] * $amount;
$database->query("INSERT INTO player_buildings (owner_id, name, power_use, life, att_inf, att_veh, att_air, att_sea)
VALUES ('$_SESSION[user_id]', '$buildings[name]', '$power_use', '$life', '$att_inf', '$att_veh', '$att_air', '$att_sea')");
$player->update();
echo "Debugg: Buildings have been added.... I hope..";
} catch (Exception $e) {
echo $e->getMessage();
}
}
// Display form
echo "<table style='width:900px;'>
<tr>
<th style='width:40% text-align:left;'>Name</th>
<th style='width:50%;'>Description</th>
<th style='width:5%;'>Price</th>
<th style='width:5%;'>Power Usage</th>
<th style='width:5%;'> </th>
</tr>";
foreach($buildings as $id => $building) {
echo "<tr>
<td>{$building['name']}</td>
<td>{$building['description']}</td>
<td>{$building['cost']}</td>
<td>{$building['power_use']}</td>
<td>
<form action='$self_link' method='POST'>
<input type='hidden' name='building_id' value='$id' />
<input style='width:40px' type='number' name='amount' value='amount' />
<input type='submit' name='build' value='Build' />
</form>
</td>
</tr>";
}
echo "</table>";
}
答案 0 :(得分:0)
SELECT entryindex, exitindex, IF(entryA < exitA, '+10', '-10')
FROM (
SELECT t1.`index` AS entryindex,
(SELECT t2.`index`
FROM mytable AS t2
WHERE t2.`index` > t1.`index` AND
((t2.`A` >= t1.`A` + 10) OR (t2.`A` <= t1.`A` - 10))
ORDER BY `index` LIMIT 1) AS exitindex,
t1.`A` AS entryA,
(SELECT t2.`A`
FROM mytable AS t2
WHERE t2.`index` > t1.`index` AND
((t2.`A` >= t1.`A` + 10) OR (t2.`A` <= t1.`A` - 10))
ORDER BY `index` LIMIT 1) AS exitA
FROM mytable AS t1
WHERE t1.`B` = 1) AS t
ORDER BY entryindex
除非 $buildings[$building['id']] = $building;
^^^^^^^^^^^^^^^
VALUES ('$_SESSION[user_id]', '$buildings[name]', '$power_[..snip..]
^^^^
解析为文字$building['id']
,否则您将访问数组中的未定义字段...
开启name
和error_reporting
进行确认 - 如果这是不正确的密钥,您将收到display_errors
警告。
另外,您可能容易受到sql injection attacks的攻击。除非您在数据库库中启用了异常,否则您只需确定查询永远不会失败。