Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

php - How to save drag moves into database

happy new year!!!

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            html,
    body {
      margin: 0;
    }
    
    table {
      border-collapse: collapse;
    }
    
    td span {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #09C;
      font-weight: bold;
    }
    
    img {
      padding: 10px;
    }
    
    #dragtable {
      border-collapse: collapse;
    }
    
    #dragtable th,
    #dragtable td {
      border: 1px solid black;
    }
        </style>
        <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="targetTable" class="b" border="10" bordercolor="blue" id="myT">
      <tbody>
        <tr>
          <td> 1</td>
          <td> 2</td>
          <td> 3</td>
          <td> 4</td>
          <td> 5</td>
          <td> 6</td>
          <td> 7</td>
          <td> 8</td>
          <td> 9</td>
          <td> 10</td>
          <td> 11</td>
          <td> 12</td>
        </tr>
        <tr>
          <td> 24</td>
          <td> 23</td>
          <td> 22</td>
          <td> 21</td>
          <td> 20</td>
          <td> 19</td>
          <td> 18</td>
          <td> 17</td>
          <td> 16</td>
          <td> 15</td>
          <td> 14</td>
          <td> 13</td>
        </tr>
      </tbody>
    </table>
    
    <table id="dragtable">
      <thead>
        <tr>
          <td>ID</td>
          <td>TO</td>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
        <script type="text/javascript">
            const items = [{
        id: 0,
        dataid: "a",
        type: "red",
        src: "https://i.imgur.com/ZEZLSOo.png",
        draggable: 2,
        position: 12,
        alt: "Norway",
      },
      {
        id: 1,
        dataid: "b",
        type: "red",
        src: "https://i.imgur.com/ZEZLSOo.png",
        draggable: 2,
        position: 12,
        alt: "Norway",
      },
      {
        id: 2,
        dataid: "a",
        type: "black",
        src: "https://i.imgur.com/dL3J8XS.jpeg",
        draggable: 2,
        position: 13,
        alt: "Norway",
      },
      {
        id: 3,
        dataid: "b",
        type: "black",
        src: "https://i.imgur.com/dL3J8XS.jpeg",
        draggable: 2,
        position: 13,
        alt: "Norway",
      }
    ]
    
    const itemHTML = (item) => {
      return `
        <span
          class="event"
          data-id="${ item.dataid }"
          draggable="${ !!item.draggable }"
        >
         ${ item.dataid } <img
            data-imgid="${ item.id }"
            src="${ item.src }"
            class="b"
            alt="${ item.alt }"
            style="width: 30%;"
          />
        </span>
      `
    }
    
    // redrawing the table based on item attributes
    const updateTable = (table, items) => {
      $(table).find('td').each(function(i, e) {
        let html = ''
        const filtered = items.filter(({
          position
        }) => position - 1 === i)
        if (filtered.length) {
          filtered.forEach(item => {
            html += itemHTML(item)
          })
        } else {
          html = !$(e).parent().index() ? i + 1 : 24 - $(e).index()
        }
        e.innerHTML = html
      })
    }
    
    updateTable('#targetTable tbody', items)
    
    const dragrowHTML = ({
      id,
      to
    }) => {
      return `<tr><td>${ id }</td><td>${ to }</td></tr>`
    }
    
    $(function() {
      initDragAndDrop();
    });
    
    function clearDragAndDrop() {
      $('.event').off();
      $('#targetTable td').off('dragenter dragover drop');
    }
    
    function initDragAndDrop() {
      $('.event').on('dragstart', function(event) {
        const itemid = event.target.getAttribute('data-imgid')
        var dt = event.originalEvent.dataTransfer;
        //add dat-attr and class from where to remove
        dt.setData('id', itemid);
      });
    
      $('.event').on('dragend', function(event) {
        clearDragAndDrop();
        initDragAndDrop();
      });
    
      // updated event handling
      $('#targetTable td').on('dragenter dragover drop', function(event) {
        event.preventDefault();
        if (event.type === 'drop') {
          const itemid = event.originalEvent.dataTransfer.getData('id');
          const item = items.find(({
            id
          }) => id == itemid)
          // if item is draggable
          if (item && item.draggable) {
            // calculate position
            item.position = ($(event.target).parent().index() * $(event.target).parent().children().length) + ($(event.target).index() + 1)
            // update table
            updateTable('#targetTable tbody', items)
            // update item's draggable property
            $('#dragtable tbody').append(dragrowHTML({
              id: item.id,
              position: item.position
            }))
            item.draggable--
          }
        }
      });
    }
        </script>
    </body>
    </html>

If you run this code then you will have a table that you actually move images through the table and creating a new table with name "dragtable". I want to save the dragtable ,into my database, the values it takes(Id and position).As a result the problem is with my php code..as you can understand it is id the image and position where it goes in the table.My php code is this

    // I fill with my  connection - I got this code from stackoverflow from another question and I fill my infos
    $pdo = 'mysql:host=localhost;dbname=backen'; 
        $username = 'root'; 
        $pwd=''; 
        try {
            $db = new PDO($pdo, $username, $pwd);
            echo"connected to database";
        }
        catch (PDOException $e) {
            $error_message = $e->getMessage();
            echo "this is displayed because an error was found";
            exit();
    }
    
    //require('path/to/pdo/connection/stateme.nts'); I didn't quite understand how that works ,nor find similar thats why I create it that up .I had similar connection require "c/dbconnect.php";
    
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);     
     //a nice guy help me with that but here I got an error on that $pdo-> , the error of lines it shows me is those  
//connected successfuly
//Fatal error: Uncaught Error: Call to a member function setAttribute() on string in //C:XampppphtdocsMyproject Stack trace: #0 {main} thrown in C:Xampppphtdocs in this line with $pdo->setAttribute
    
    $query = "
    SELECT *
      FROM my_table
     ORDER
        BY position
    ";
    $stmt  = $pdo->prepare($query);
    
    $stmt->execute();
    $data  = $stmt->fetchAll();
    print_r($data);
    
    $query = "
    UPDATE my_table x
      JOIN
         ( SELECT image
                , position old_order
                , ROUND(CASE WHEN position NOT BETWEEN LEAST(:old_position,:new_position) AND GREATEST(:old_position,:new_position)
                             THEN position
                             WHEN position = :old_position THEN :new_position
                             ELSE position+(((:old_position>:new_position)-.5)*2)
                             END
                       ,0) new_order
             FROM my_table
         ) y
        ON y.image = x.image
       SET position = new_order
    ";
    
    $old_position  = $_GET['old_position'];
    $new_position  = $_GET['new_position'];
    
    $stmt  = $pdo->prepare($query);
    $stmt->execute(array('old_position' => $old_position,'new_position' => $new_position));
    
    ?>

Let's do a conclusion,

  1. First,I am connected - It shows me message connected to database,I added that to my code.I think I am ok with that part.
  2. Second on that line I have error with I search it but I didn't managed to do that $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE); 3.For more information,not to solve it if it is difficult,is there another way to pass the dragtable table ( the dragging moves) into a database except for that way? if you can find another way I to do it ,because I can't figure out a way to do that..or send me similar ways how to do it ,because I am searching so long how to put my table into a database.As a result the next time someone will get in will remember "saved" the moves I did. Thanks in advance.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...