如何使用ajax php和mysql进行保存和编辑?

时间:2016-03-26 03:23:21

标签: php mysql ajax

我需要用ajax php和mysql来保存和编辑,但我不太了解ajax。

我在保存和编辑数据库中的新记录时遇到问题。

以下是我的代码,以便于理解。

我很感谢你的帮助。

index.php

res.cookie('uuid', uuid);

dbcontroller.php

<style>
body{width:40%;}
.message-box{margin-bottom:20px;border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;}
.btnEditAction{background-color:#45619D;border:0;padding:2px 10px;color:#FFF;}
.btnSaveAction{background-color:#2FC332;border:0;padding:2px 10px;color:#FFF; position: relative; top: -19px; z-index: 10;}
.btnsave{background-color:#2FC332;border:0;padding:2px 10px;color:#FFF; position: relative; top: -19px; z-index: 10;}
.salvar2{display: none !important;}
</style>

<?php
    require_once("dbcontroller.php");
    $db_handle = new DBController();
    $comments = $db_handle->runQuery("SELECT * FROM comment");
?>

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

<script>

function showEditBox(editobj,id) {
    $('.valor').show();
    $('.salvar').addClass('salvar2');
    $('#frmAdd').show();
    $(editobj).prop('disabled','true');
    var currentMessage = $("#message_" + id + " .message-content").html();
    var editMarkUp = '<button name="ok" class="btnSaveAction" onClick="callCrudAction(\'edit\','+id+')">Save</button><textarea class="valor2" rows="5" cols="80" id="txtmessage_'+id+'">'+currentMessage+'</textarea>';
    $("#message_" + id + " .message-content").html(editMarkUp);
    $('.btnSaveAction').show();
}

function callCrudAction(action,id) {
     $("#loaderIcon").show();
     var queryString;
     switch(action) {
         case "edit":
        queryString = 'action='+action+'&message_id='+ id + '&txtmessage='+ $("#txtmessage_"+id).val();
    break;
    case "save":
        queryString = 'action='+action+'&message_id='+ id + '&txtmessage='+ $("#txtmessage_"+id).val();
    break;
}    
jQuery.ajax({
url: "crud_action.php",
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
        case "edit":
            $('.valor').hide();
            $('.salvar').addClass('salvar2');
            $('.btnEditAction').show();
            $("#message_" + id + " .message-content").html(data);
            $('#frmAdd').show();
            $("#message_"+id+" .btnEditAction").prop('disabled','');
        break;

        case "save":
            $('.valor').hide();
            $('.salvar').addClass('salvar2');
            $('.btnEditAction').show();
            $("#message_" + id + " .message-content").html(data);
            $('#frmAdd').show();
            $("#message_"+id+" .btnEditAction").prop('disabled','');
        break;
    }
    $("#txtmessage").val('');
    $("#loaderIcon").hide();
},
error:function (){}
});
}
</script>

<div class="form_style">
<div id="comment-list-box">
<?php
    if(!empty($comments)) {
    foreach($comments as $k=>$v) { ?>

<script type="text/javascript">
    var indice = "<?php echo $comments[$k]["id"];?>";
</script>

<div class="message-box" id="message_<?php echo $comments[$k]["id"];?>">
<div>
<?php if($v['message'] != "") { ?>
<button class="btnEditAction" name="edit" onClick="showEditBox(this,<?php echo $comments[$k]["id"]; ?>)">Edit</button>
<?php } ?>
<?php if($v['message'] == "") { ?>
     <button style="display: none" class="btnEditAction" name="edit" onClick="showEditBox(this,<?php echo $comments[$k]["id"]; ?>)">Edit</button>
     <button name="ok" class="btnSaveAction salvar" onClick="callCrudAction('save','indice')">Save</button><textarea class="valor" rows="5" cols="80" id="txtmessage_'<?php echo $comments[$k]["id"]; ?>'"></textarea>
<?php } ?>
</div>
<div class="message-content"><?php echo $comments[$k]["message"]; ?></div>
</div>
<?php
}
} ?>
</div>

<img src="LoaderIcon.gif" id="loaderIcon" style="display:none" />
</div>

crud_action.php

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

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;   
}
}
?>

database.sql

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();

$action = $_POST["action"];
if(!empty($action)) {
switch($action) {           
    case "edit":
        $result = mysql_query("UPDATE comment set message = '".$_POST["txtmessage"]."' WHERE  id=".$_POST["message_id"]);
        if($result){
              echo $_POST["txtmessage"];
        }
        break;

    case "save":
        $result = mysql_query("UPDATE comment set message = '".$_POST["txtmessage"]."' WHERE  id=".$_POST["message_id"]);
        if($result){
              echo $_POST["txtmessage"];
        }
        break;          
    }
}
?>

1 个答案:

答案 0 :(得分:0)

它实际上工作得很好。您只是错过了在crud_action.php中调用的插入函数。我为此创建了一个存储过程,以便对其进行参数化并返回新的ID。

我还在你的DDL中使用了一个自动递增的主键。

这至少有效,但您仍应非常关注使用mysqli functions SANITIZE 您的输入 - 我会留给您和google,因为有很多例子。

然后你需要一个空白的“新”文本区来获取新的评论,并完成对它的ajax调用的实现。

它目前散布的错误行为是因为你处理空值的方式。要清理它,你只需要摆脱空值列的笨重冗余空白文本区域。

的index.php

<style>
body{width:40%;}
.message-box{margin-bottom:20px;border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;}
.btnEditAction{background-color:#45619D;border:0;padding:2px 10px;color:#FFF;}
.btnSaveAction{background-color:#2FC332;border:0;padding:2px 10px;color:#FFF; position: relative; top: -19px; z-index: 10;}
.btnsave{background-color:#2FC332;border:0;padding:2px 10px;color:#FFF; position: relative; top: -19px; z-index: 10;}
.salvar2{display: none !important;}
</style>

<?php
    require_once("dbcontroller.php");
    $db_handle = new DBController();
    $comments = $db_handle->runQuery("SELECT * FROM comment");
?>

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

<script>

function showEditBox(editobj,id) {
    $('.valor').show();
    $('.salvar').addClass('salvar2');
    $('#frmAdd').show();
    $(editobj).prop('disabled','true');
    var currentMessage = $("#message_" + id + " .message-content").html();
    var editMarkUp = '<button name="ok" class="btnSaveAction" onClick="callCrudAction(\'edit\','+id+')">Save</button><textarea class="valor2" rows="5" cols="80" id="txtmessage_'+id+'">'+currentMessage+'</textarea>';
    $("#message_" + id + " .message-content").html(editMarkUp);
    $('.btnSaveAction').show();
}

function callCrudAction(action,id) {
     $("#loaderIcon").show();
     var queryString;
     switch(action) {
         case "edit":
        queryString = 'action='+action+'&message_id='+ id + '&txtmessage='+ $("#txtmessage_"+id).val();
    break;
    case "save":
        queryString = 'action='+action+'&message_id='+ id + '&txtmessage='+ $("#txtmessage_"+id).val();
    break;
}    
jQuery.ajax({
url: "crud_action.php",
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
        case "edit":
            $('.valor').hide();
            $('.salvar').addClass('salvar2');
            $('.btnEditAction').show();
            $("#message_" + id + " .message-content").html(data);
            $('#frmAdd').show();
            $("#message_"+id+" .btnEditAction").prop('disabled','');
        break;

        case "save":
            $('.valor').hide();
            $('.salvar').addClass('salvar2');
            $('.btnEditAction').show();
            $("#message_" + id + " .message-content").html(data);
            $('#frmAdd').show();
            $("#message_"+id+" .btnEditAction").prop('disabled','');
        break;
    }
    $("#txtmessage").val('');
    $("#loaderIcon").hide();
},
error:function (){}
});
}

function create_comment(){
  var payload = "action=save&txtmessage=" + $("#newComment").val();
  console.log(payload);
  $.ajax({
    method: "POST",
    url: "crud_action.php",
    data: payload,
    success: function(result_id){
      console.log(result_id);
      // clone the template
      var new_msg_box = $("#msgBoxTemplate").clone();
      // set the new ID
      new_msg_box.attr("id","message_"+result_id);
      // set the edit ajax ID
      new_msg_box.find("button").attr("onClick","showEditBox(this,"+result_id+")");
      // set the message content
      new_msg_box.children(".message-content").text($("#newComment").val());
      // clear the new message textarea
      $("#newComment").val("");
      // show the new message
      $("#comment-list-box").append(new_msg_box);
      new_msg_box.show();
    }
  });
}

</script>

<div class="form_style">
  <div id="comment-list-box">
  <?php
  if(!empty($comments)) {
    foreach($comments as $k=>$v) { ?>

      <div class="message-box" id="message_<?php echo $comments[$k]["id"];?>">
        <div>
          <button class="btnEditAction" name="edit" onClick="showEditBox(this,<?php echo $comments[$k]["id"]; ?>)">Edit</button>
        </div>
        <div class="message-content"><?php echo $comments[$k]["message"]; ?></div>
      </div>

    <?php } // END foreach
  } // END if(!empty($comments)) ?>
  </div>

<textarea class="valor2" rows="5" cols="80" id="newComment"></textarea>
<button name="ok" class="btnSaveAction" onClick="create_comment()">Create New</button>
</div>

<!-- template for cloning -->
<div class="message-box" id='msgBoxTemplate' style='display:none'>
  <div>
    <button class="btnEditAction" name="edit">Edit</button>
  </div>
  <div class="message-content"></div>
</div>

crud_action.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$action = $_POST["action"];
if(!empty($action)) {
switch($action) {           
    case "edit":
        // SANITIZE HERE
        $result = mysql_query("UPDATE comment set message = '".$_POST["txtmessage"]."' WHERE  id=".$_POST["message_id"]);
        if($result){
              echo $_POST["txtmessage"];
        }
        break;

    case "save":
        // SANITIZE HERE
        $result = mysql_query("CALL create_comment('".$_POST["txtmessage"]."')");
        if($result){
              $row = mysql_fetch_assoc($result);
              echo $row["new_id"];
        }
        break;          
    }
}
?>

database.sql

DROP TABLE IF EXISTS `comment`;
CREATE TABLE IF NOT EXISTS `comment` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `message` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `comment` (`message`) VALUES
('first comment'),
('2nd comment'),
('3rd comment'),
('4th comment');

DROP PROCEDURE IF EXISTS create_comment;
DELIMITER $$
CREATE PROCEDURE create_comment( 
  p_message VARCHAR(100)
)
this_procedure:BEGIN
  INSERT INTO `comment` (`message`)
  VALUES (p_message);
  SELECT LAST_INSERT_ID() AS 'new_id';
END $$
DELIMITER ;