简体   繁体   English

与数据库PHP和MYSQL可拖动

[英]Draggable With Database PHP and MYSQL

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. 我正在尝试使其加载到画布中,然后将Items拖放到其上的任何位置,然后有一个保存按钮来保存它。

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 www.lupekid.com


EDIT: 编辑:

If you look at my site, I only have done it though PHP Clicks. 如果您查看我的网站,则只能通过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 jsfiddle.net/jakecigar/v685v9t6/31

but I'm not sure how to integrate it with my database, I'm not that familiar with jQuery. 但我不确定如何将其与数据库集成,我对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>';
    }

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 : 让我们有一个表来存储不同类型的家具,将其命名为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 : 然后在您的myitems表上,我们将为保存的位置添加更多列,并将itemName列替换为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. 因此,当您加载它们时( 让我们使用prepared statement ),您可以像这样( 使用LEFT JOIN )来加载所有分配给用户的家具。 We will also use the fetched left_position and top_position column to the style tag to position them inside the containment-wrapper : 我们还将在style标签中使用提取的left_positiontop_position列,将它们放置在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. 让我们创建您的jQuery脚本。 We will get the current position of each div.draggable and Ajax to save the new position to the database. 我们将获取每个div.draggableAjax的当前位置,以将新位置保存到数据库中。

/* 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: 您会注意到,我们将数据传递到save-position.php ,因此让我们创建此文件:

/*** 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. 但是在此示例中,它不会保存位置,因为我们没有用于保存数据的数据库。

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. 您可以做的是在php中的任何位置编写html,并在html中使用script标签为可拖动项创建代码,这些代码将通过jquery库和jquery可拖动插件包括在内。

Hope this helps 希望这可以帮助

    <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. 在coordsave.php中,您可以从ajax获取信息并按位置发送到数据库。 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... 载入所有玩家信息的页面后,也放置物品位置并显示出来...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM