Home Ask Login Register

Developers Planet

Your answer is one click away!

Naxor February 2016

php Array values dont get inported to DB

I'm building a browser game in order to learn html,css,php and MySQL. And i wrote the code below to allow players to build new buildings. The table loads with all buildings, and everything work fine, even the insert to the DB. But as i'm new to this i have a problem where all the values that should be put into the DB are empty. the $_SESSION[user_id] works. But not the values from the array. So i think the problem might be that i dont know how to get the values correctly..

So if someone would like to help me here it would be much appreciated and educational for me! :)

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')");

            echo "Debugg: Buildings have been added.... I hope..";
        } catch (Exception $e) {
            echo $e->getMessage();

    // Display form 
    echo "<table style='width:900px;'>
            <th style='width:40% text-align:left;'>Name</th>
            <th style='        


Marc B February 2016

    $buildings[$building['id']] = $building;

    VALUES ('$_SESSION[user_id]', '$buildings[name]', '$power_[..snip..]

Unless $building['id'] resolves into the literal word name, you're accessing undefined fields in your array...

Turn on error_reporting and display_errors to confirm - if that is an incorrect key, you'll get undefined index warnings.

Plus you're likely vulnerable to sql injection attacks. And unless you've enabled exceptions in your DB library, you're simply ASSUMING the query will never fail.

Post Status

Asked in February 2016
Viewed 3,226 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life