0

So I'm making a Video Game online, and my players have Inventory and Profiles.

I'm trying to make it Load the Inventory into a Canvas, and then make the Items Draggable anywhere on it, then there's a Save Button to save it.

So it will only Load the Items it has Added into The Room already. So lets say I added a Chair, Desk, Bed from inventory into The Database, Room.

Those items should show up on the Profile.

But how can I make them move and Draggable with a Save Button?

This is my site right now if you want to check it out. www.lupekid.com


EDIT:

If you look at my site, I only have done it though PHP Clicks. But I'm trying to change it to do Draggable and I'm not sure where to start. I'm trying to do it like this:

jsfiddle.net/jakecigar/v685v9t6/31

but I'm not sure how to integrate it with my database, I'm not that familiar with jQuery.

public function DisplayMyBeds2()
{

    $myuserid = $_SESSION['user_id'];
    // This first query is just to get the total count of rows
    $sql = "SELECT COUNT(*) FROM myitems WHERE (user_id='$myuserid' AND itemCategory='bed')";
    $query = mysqli_query($this->_con, $sql);
    $row = mysqli_fetch_row($query);
    // Here we have the total row count
    $rows = $row[0];
    // This is your query again, it is for grabbing just one page worth of rows by applying $limit
    $sql = "SELECT * FROM myitems WHERE (user_id='$myuserid' AND itemCategory='bed') ORDER BY itemId ASC";
    $query = mysqli_query($this->_con, $sql);
    $list = '';
    $count = mysqli_num_rows($row);

    echo '<div id="message" style="display:none"><h1>Saved!</h1></div>';

    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

        echo '
            <div id="containment-wrapper">
                <div id="bed'.$row["itemId"].'" class="ui-widget-content draggable" data-left="20px" data-top="20px" style="position: absolute; left:20px; top:20px">'.$row["itemName"].'</div>
            </div>';
    }
Logan Wayne
  • 5,884
  • 15
  • 29
  • 47
LupeKid
  • 3
  • 4
  • 1
    Please conform to simple reproducible examples with code. We wouldn't want to register to an unknown source game, that might steal our accounts to test what You want to do. – ntohl Jun 02 '16 at 07:47
  • Can you show us what you have tried? – GROVER. Jun 02 '16 at 07:48
  • if you look at my site i only have done it Though PHP Clicks. But im trying to Change it to do Draggable im not sure where to start. im trying to do it like this , https://jsfiddle.net/jakecigar/v685v9t6/31/ but im not sure how to integrate it with my database, im not that familar with jq – LupeKid Jun 02 '16 at 07:57
  • @LupeKid - what is the table structure of your items? – Logan Wayne Jun 02 '16 at 09:18
  • @Logan Wayne , hey mate the Fiddle you have in your profile, is exacly what i need :D! https://jsfiddle.net/Logan_Wayne/ru1a3npc/ . However i want to add this new Comment edited – LupeKid Jun 02 '16 at 22:53
  • @LoganWayne Do you happen to have Private mesasge or Skype something? i like your Fiddle im pretty sure it will work with my code somehow :P i added a little example? check it out please thank you – LupeKid Jun 02 '16 at 23:02
  • @LupeKid - oh yeah, I was working my answer for you yesterday, but I did not hear anything from you since then so I halt my code. I'll try to post my answer today. – Logan Wayne Jun 03 '16 at 00:08

3 Answers3

3

Lets try to change a bit your table structure. Lets have a table where you store different types of furniture, lets name it furniture_tb:

 fur_id | furniture |  fur_image
--------+-----------+-------------
    1   |   chair   |   chair.png
    2   |   table   |   table.png
    3   |   couch   |   couch.png
    4   |   window  |   window.png

Then on your myitems table, we will add more columns for their saved position, and we will replace the itemName column with just the fur_id:

 itemId | user_id | fur_id | left_position | top_position 
--------+---------+--------+---------------+--------------
    1   |    1    |    1   |     20px      |      20px
    2   |    1    |    2   |     97px      |      102px 
    3   |    1    |    3   |     98px      |      20px
    4   |    1    |    4   |     176px     |      20px

So when you load them (lets use prepared statement), you can have it like this (using LEFT JOIN) where it will load all the furnitures that was assigned to the user. We will also use the fetched left_position and top_position column to the style tag to position them inside the containment-wrapper:

echo '<div id="message" style="display:none"><h1>Saved!</h1></div>
      <div id="containment-wrapper">';

$stmt = $con->prepare("SELECT a.itemId, 
                              a.left_position,
                              a.top_position,
                              b.furniture,
                              b.fur_image
                       FROM myitems a
                       LEFT JOIN furniture_tb b ON a.fur_id = b.fur_id WHERE user_id = ?");
$stmt->bind_param("i", $myuserid); /* REPLACE THE ? IN THE QUERY ABOVE WITH $myuserid; i STANDS FOR INTEGER */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($itemid, $leftpos, $toppos, $furniture, $furimage); /* BIND THE RESULT TO THESE VARIABLES */
while($stmt->fetch()){ /* FETCH ALL RESULTS */

    echo '<div id="'.$itemid.'" class="ui-widget-content draggable" style="position: absolute; left:'.$leftpos.'; top:'.$toppos.'">'.$furniture.'</div>';

}
$stmt->close(); /* CLOSE PREPARED STATEMENT */

echo '</div><!-- CONTAINMENT-WRAPPER -->';

Lets create your jQuery script. We will get the current position of each div.draggable and Ajax to save the new position to the database.

/* GRANT THE DIV WITH draggable CLASS TO BE DRAGGABLE */
$(document).on("ready", function(){ 
    $(".draggable").draggable({
        containment: "#containment-wrapper"
    });
})

/* WHEN USER HIT THE SAVE BUTTON */
$(document).on("ready", "#save", function(){

    $(".draggable").each(function(){ /* RUN ALL FURNITURE */

        var elem = $(this),
            id = elem.attr('id'), /* GET ITS ID */
            pos = elem.position(),
            newleft = pos.left+'px', /* GET ITS NEW LEFT POSITION */
            newtop = pos.top+'px'; /* GET ITS NEW TOP POSITION */

        $.ajax({ /* START AJAX */
            type: 'POST', /* METHOD TO PASS THE DATA */
            url: 'save-position.php', /* FILE WHERE WE WILL PROCESS THE DATA */
            data: {'id':id, 'newleft': newleft, 'newtop':newtop}, /* DATA TO BE PASSED TO save-position.php */
            success: function(result){
                $("#message").show(200); /* SHOW THE SUCCESS SAVE MESSAGE */
            }
        })            

    })

})

You will notice that we pass the data to save-position.php, so lets create this file:

/*** INCLUDE YOUR DATABASE CONNECTION HERE FIRST ***/

if(!empty($_POST["id"]) && !empty($_POST["newleft"]) && !empty($_POST["newtop"])){

    $stmt = $con->prepare("UPDATE myitems SET left_position = ?, top_position = ? WHERE itemId = ?"); /* PREPARE YOUR UPDATE QUERY */
    $stmt->bind_param("ssi", $_POST["newleft"], $_POST["newtop"], $_POST["id"]); /* BIND THESE PASSED VARIABLES TO THE QUERY ABOVE; s STANDS FOR STRINGS; i STANDS FOR INTEGER */
    $stmt->execute(); /* EXECUTE QUERY */
    $stmt->close(); /* CLOSE PREPARED STATEMENT */

}

You can look at this fiddle for example. But it will not save the position in this example because we don't have a database to save the data with.

Logan Wayne
  • 5,884
  • 15
  • 29
  • 47
  • Thank you ill try and add this to my code :), i cant change the table because im using, a items.php Cotainng the Items and ids :P..... DO you happen to have SKYPE or instant messager ? i can talk to you :P ill post back here with an update later today :) – LupeKid Jun 03 '16 at 03:30
  • @LupeKid - Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113695/logan-wayne-and-lupe-kid). – Logan Wayne Jun 03 '16 at 03:48
  • Sadly i dont have 20 rep – LupeKid Jun 03 '16 at 06:04
  • @LupeKid - oww. So what happened? Did you try my answer in your project? What is the outcome? – Logan Wayne Jun 03 '16 at 06:34
  • Yes i was able to do it, I modified your Code, But now im not sure how to save it :P Altho you have been very helpful and made it posible :D items now load on the Drag Screen :D , And now i need to be able to save em :P Thers an X And Y In the DataBase, ItemID , X , Y .. Ill report back after i try it :),, is this mysqli injection save the AJAX?? – LupeKid Jun 03 '16 at 06:46
  • @LupeKid - use Ajax to save the position of those divs which I already posted in my answer. And read more about [How to prevent SQL injections](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). It is better to use prepared statement which I used on my answer above. – Logan Wayne Jun 03 '16 at 06:50
  • ill report back later today :) Thank you My web Cpanel is downright now, But ill look into that im using MYSQLI so il change it into that, Ill report back later today or tomorrow thank you for all the help :) My site is coming out great now i spent like over 50 hours looking on how to do this, and you helpped me so much i wish i can repay you in a way. – LupeKid Jun 03 '16 at 06:53
  • @LupeKid - well, if my answer helps you, you can just up-vote or accept my answer. But that is after you implement my answer properly to your project. Goodluck! – Logan Wayne Jun 03 '16 at 06:56
  • my save function isnt working ;/ this is what i have ... http://pastebin.com/YjF42hmy , it just reloads the page nothing happens, and my Table looks like this . http://puu.sh/pgR8o/6ad3aa6deb.png – LupeKid Jun 04 '16 at 21:20
0

What you can do is write your html anywhere within your php and in html use script tag to create code for your draggable items, which you will include via the jquery library and the jquery draggable plugin.

Hope this helps

Gustav Coetzee
  • 49
  • 1
  • 10
0
    <script type="text/javascript">
$(document).ready(function() {
$("YOUR_ITEM").draggable({ 
containment: 'parent',  

containment: 'parent', - This is for area where you want to be saved only.. Perhaps you item is standing into div one and yu want to put it only somewhere inside div two...

  stop: function(event, ui) {
      var pos_x = ui.offset.left;
      var pos_y = ui.offset.top;

      //Do the ajax call to the server
      $.ajax({
          type: "POST",
          url: "coordsave.php",
          data: {x: pos_x, y: pos_y}
        }).done(function( msg ) {
          alert( "Data Saved: " + msg );
        }); 
  }
 });
});
</script>

Inside coordsave.php you can have just getting info from ajax and send to database by positions. And on your game for that profile which added item with that coords like. You can make new field in database as new item and that field contains only position. After loaded page with all player info put items positions as well and show them up...