How to implement editable table, updating the fields in the database automatically

8

I have the following table that lets you edit cells directly:

The codes are in 4 parts:

  

MySQL table

CREATE TABLE IF NOT EXISTS 'php_interview_questions' (
'id' int(8) NOT NULL,
  'question' text NOT NULL,
  'answer' text NOT NULL,
  'row_order' int(8) NOT NULL
)

INSERT INTO 'php_interview_questions' ('id', 'question', 'answer', 'row_order') VALUES
(1, 'PHP array functions example', 'is_array(), in_array(), array_keys(),array_values()', 3),
(2, 'How to redirect using PHP', 'Using header() function', 4),
(3, 'Differentiate PHP size() and count():', 'Same. But count() is preferable.', 1),
(4, 'What is PHP?', 'A server side scripting language.', 0),
(5, 'What is php.ini?', 'PHP configuration file.', 2);
  

DB Controller:

<?php
class DBController {
    private $host = "localhost";
    private $user = "root";
    private $password = "";
    private $database = "blog_examples";

    function __construct() {
        $conn = $this->connectDB();
        if(!empty($conn)) {
            $this->selectDB($conn);
        }
    }

    function connectDB() {
        $conn = mysql_connect($this->host,$this->user,$this->password);
        return $conn;
    }

    function selectDB($conn) {
        mysql_select_db($this->database,$conn);
    }

    function runQuery($query) {
        $result = mysql_query($query);
        while($row=mysql_fetch_assoc($result)) {
            $resultset[] = $row;
        }       
        if(!empty($resultset))
            return $resultset;
    }

    function numRows($query) {
        $result  = mysql_query($query);
        $rowcount = mysql_num_rows($result);
        return $rowcount;   
    }
}
?>
  

index.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$sql = "SELECT * from php_interview_questions";
$faq = $db_handle->runQuery($sql);
?>
<html>
    <head>
      <title>PHP MySQL Inline Editing using jQuery Ajax</title>
        <style>
            body{width:610px;}
            .current-row{background-color:#B24926;color:#FFF;}
            .current-col{background-color:#1b1b1b;color:#FFF;}
            .tbl-qa{width: 100%;font-size:0.9em;background-color: #f5f5f5;}
            .tbl-qa th.table-header {padding: 5px;text-align: left;padding:10px;}
            .tbl-qa .table-row td {padding:10px;background-color: #FDFDFD;}
        </style>
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script><script><script>functionshowEdit(editableObj){$(editableObj).css("background","#F0E68C");
    } 

    function saveToDatabase(editableObj,column,id) {
        $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
        $.ajax({
            url: "saveedit.php",
            type: "POST",
            data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
            success: function(data){
                $(editableObj).css("background","#FDFDFD");
            }        
       });
    }
    function checkEnter(e, editableObj, column, id){
       if (e.keyCode == 13 && e.shiftKey == false) {
          saveToDatabase(editableObj, column, id);
          e.preventDefault();
       }
    }

        </script>
    </head>
    <body>      
       <table class="tbl-qa">
          <thead>
              <tr>
                <th class="table-header" width="10%">Q.No.</th>
                <th class="table-header">Question</th>
                <th class="table-header">Answer</th>
              </tr>
          </thead>
          <tbody>
          <?php
          foreach($faq as $k=>$v) {
          ?>
              <tr class="table-row">
                <td><?php echo $k+1; ?></td>
                <td contenteditable="true" 
                onBlur="saveToDatabase(this,'answer2','<?php echo $faq[$k]["id"]; ?>')"
                onKeyDown="checkEnter(event, this,'answer2','<?php echo $faq[$k]["id"]; ?>')" 
                onClick="showEdit(this);"><?php echo $faq[$k]["question"]; ?></td>
                <td contenteditable="true" onBlur="saveToDatabase(this,'answer','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $faq[$k]["answer"]; ?></td>
              </tr>
        <?php
        }
        ?>
          </tbody>
        </table>
    </body>
</html>
  

saveedit.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("UPDATE php_interview_questions set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE  id=".$_POST["id"]);
?>

The change I need should, after changing the text of a field and clicking outside the table (losing focus), update the data in the database.

How could I do this?

    
asked by anonymous 20.01.2017 / 19:20

1 answer

5

I made some changes to your files, summarizing:

  • Do not use mysql _ , use mysqli _
  • When you run an UPDATE command, the expected result is TRUE and not "mysqli_result" to pass to the mysqli_fetch_assoc function, so you have to change the RunQuery     $ result = mysqli_query ($ this- > connection, $ query);

    if (( $result !== false ) && ( $result !== true ) )
    {
        while($row=mysqli_fetch_assoc($result)) 
        {
            $resultset[] = $row;
        }                               
    }
    
  • To check the parameters that JQUERY sends during Ajax, construct a BeforeSend method.

    $.ajax({
        url: "saveedit.php",
        type: "POST",
        data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
        beforeSend: function(){ console.log('column='+column+'&editval='+editableObj.innerHTML+'&id='+id); },
        success: function(data){
            $(editableObj).css("background","#FDFDFD");
        }        
    });
    
  • When constructing the table, in the first column, did you spell the parameters wrong: answer2 ?

  •     onBlur="saveToDatabase(this,'answer2','<?php echo $faq[$k]["id"]; ?>;')"
        onKeyDown="checkEnter(event, this,'answer2','<?php echo $faq[$k]["id"]; ?>')"
        onClick="showEdit(this);"><?php echo $faq[$k]["question"]; ?></td>  

    To see the result download this file: link

        
    14.02.2017 / 23:10