2017-09-23 37 views
0

好吧,這是一個包含添加/編輯/刪除選項的粗糙應用程序,我想實現以添加其他按鈕來查看選定的行,但我的查詢不起作用,我使用Ajax發送一個http請求並獲取數據,但查詢不起作用。SQL SELECT語句+ Ajax不能正常工作

Form_view.html

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title></title> 
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all"> 
<link href="dist/jquery.bootgrid.css" rel="stylesheet" /> 
<script src="dist/jquery-1.11.1.min.js"></script> 
<script src="dist/bootstrap.min.js"></script> 
<script src="dist/jquery.bootgrid.min.js"></script> 
</head> 
<body> 
    <div class="container"> 
     <div class=""> 
     <h1></h1> 
     <div class="col-sm-8"> 
     <div class="well clearfix"> 
      <div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0"> 
      <span class="glyphicon glyphicon-plus"></span> Record</button></div></div> 
     <table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid"> 
      <thead> 
       <tr> 
        <th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th> 
        <th data-column-id="employee_name">Name</th> 
        <th data-column-id="employee_salary">Salary</th> 
        <th data-column-id="employee_age">Age</th> 
        <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th> 
       </tr> 
      </thead> 
     </table> 
    </div> 
     </div> 
    </div> 

<div id="add_model" class="modal fade"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
       <h4 class="modal-title">Add Employee</h4> 
      </div> 
      <div class="modal-body"> 
       <form method="post" id="frm_add"> 
       <input type="hidden" value="add" name="action" id="action" > 
        <div class="form-group"> 
        <label for="name" class="control-label">Name:</label> 
        <input type="text" class="form-control" id="name" name="name" required></input> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Salary:</label> 
        <input type="text" class="form-control" id="salary" name="salary" required></input> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Age:</label> 
        <input type="text" class="form-control" id="age" name="age" required></input> 
        </div> 

      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <button type="button" id="btn_add" class="btn btn-primary">Save</button> 
      </div> 
      </form> 
     </div> 
    </div> 
</div> 
<div id="edit_model" class="modal fade"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
       <h4 class="modal-title">Edit Employee</h4> 
      </div> 
      <div class="modal-body"> 
       <form method="post" id="frm_edit"> 
       <input type="hidden" value="edit" name="action" id="action"> 
       <input type="hidden" value="0" name="edit_id" id="edit_id"> 
        <div class="form-group"> 
        <label for="name" class="control-label">Name:</label> 
        <input type="text" class="form-control" id="edit_name" name="edit_name"> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Salary:</label> 
        <input type="text" class="form-control" id="edit_salary" name="edit_salary"/> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Age:</label> 
        <input type="text" class="form-control" id="edit_age" name="edit_age"/> 
        </div> 

      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <button type="button" id="btn_edit" class="btn btn-primary">Save</button> 
      </div> 
      </form> 
     </div> 
    </div> 
</div> 


<div id="view_model" class="modal fade"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
       <h4 class="modal-title">View Employee</h4> 
      </div> 
      <div class="modal-body"> 
       <form method="post" id="frm_view"> 
       <input type="hidden" value="view" name="action" id="action"> 
       <input type="hidden" value="0" name="view_id" id="view_id"> 


        <div class="form-group"> 
        <label for="name" class="control-label">Name:</label> 
        <input type="text" class="form-control" id="view_name" name="view_name"> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Salary:</label> 
        <input type="text" class="form-control" id="view_salary" name="view_salary"/> 
        </div> 
        <div class="form-group"> 
        <label for="salary" class="control-label">Age:</label> 
        <input type="text" class="form-control" id="view_age" name="view_age"/> 
        </div> 

      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <button type="button" id="btn_view" class="btn btn-primary">Save</button> 
      </div> 
      </form> 
     </div> 
    </div> 
</div> 



</body> 
</html> 
<script type="text/javascript"> 
$(document).ready(function() { 
    var grid = $("#employee_grid").bootgrid({ 
     ajax: true, 
     rowSelect: true, 
     post: function() 
     { 
      /* To accumulate custom parameter with the request object */ 
      return { 
       id: "b0df282a-0d67-40e5-8558-c9e93b7befed" 
      }; 
     }, 

     url: "response.php", 
     formatters: { 
       "commands": function(column, row) 
       { 
        return "<button type=\"button\" class=\"btn-success btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " + 
         "<button type=\"button\" class=\"btn-danger btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button> " + 
         "<button type=\"button\" class=\"btn-warning btn-default command-view\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-eye-open\"></span></button>"; 
       } 
      } 
    }).on("loaded.rs.jquery.bootgrid", function() 
{ 
    /* Executes after data is loaded and rendered */ 
    grid.find(".command-edit").on("click", function(e) 
    { 
     //alert("You pressed edit on row: " + $(this).data("row-id")); 
      var ele =$(this).parent(); 
      var g_id = $(this).parent().siblings(':first').html(); 
      var g_name = $(this).parent().siblings(':nth-of-type(2)').html(); 
console.log(g_id); 
        console.log(g_name); 

     //console.log(grid.data());// 
     $('#edit_model').modal('show'); 
        if($(this).data("row-id") >0) { 

           // collect the data 
           $('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key 
           $('#edit_name').val(ele.siblings(':nth-of-type(2)').html()); 
           $('#edit_salary').val(ele.siblings(':nth-of-type(3)').html()); 
           $('#edit_age').val(ele.siblings(':nth-of-type(4)').html()); 
        } else { 
        alert('Now row selected! First select row, then click edit button'); 
        } 
    }).end() 


    //View data 

    grid.find(".command-view").on("click", function(e) 
    { 
     //alert("You pressed edit on row: " + $(this).data("row-id")); 
      var ele =$(this).parent(); 
      var g_id = $(this).parent().siblings(':first').html(); 
      var g_name = $(this).parent().siblings(':nth-of-type(2)').html(); 
      console.log(g_id); 
        console.log(g_name); 

     //console.log(grid.data());// 
     $('#view_model').modal('show'); 
        if($(this).data("row-id") >0) { 

           // collect the data 
           $('#view_id').val(ele.siblings(':first').html()); // in case we're changing the key 
           $('#view_name').val(ele.siblings(':nth-of-type(2)').html()); 
           $('#view_salary').val(ele.siblings(':nth-of-type(3)').html()); 
           $('#view_age').val(ele.siblings(':nth-of-type(4)').html()); 
        } else { 
        alert('error'); 
        } 
    }).end() 

    //end view data 


    grid.find(".command-delete").on("click", function(e) 
    { 

     var conf = confirm('Delete ' + $(this).data("row-id") + ' items?'); 
        alert(conf); 
        if(conf){ 
           $.post('response.php', { id: $(this).data("row-id"), action:'delete'} 
            , function(){ 
             // when ajax returns (callback), 
             $("#employee_grid").bootgrid('reload'); 
           }); 
           //$(this).parent('tr').remove(); 
           //$("#employee_grid").bootgrid('remove', $(this).data("row-id")) 
        } 
    }); 
}); 

function ajaxAction(action) { 
       data = $("#frm_"+action).serializeArray(); 
       $.ajax({ 
        type: "POST", 
        url: "response.php", 
        data: data, 
        dataType: "json",  
        success: function(response) 
        { 
        $('#'+action+'_model').modal('hide'); 
        $("#employee_grid").bootgrid('reload'); 
        } 
       }); 
      } 

      $("#command-add").click(function() { 
       $('#add_model').modal('show'); 
      }); 
      $("#btn_add").click(function() { 
       ajaxAction('add'); 
      }); 
      $("#btn_edit").click(function() { 
       ajaxAction('edit'); 
      }); 
      $("#btn_view").click(function() { 
       ajaxAction('view'); 
      }); 
}); 
</script> 

response.php

<?php 
    //include connection file 
    include_once("connection.php"); 

    $db = new dbObj(); 
    $connString = $db->getConnstring(); 

    $params = $_REQUEST; 

    $action = isset($params['action']) != '' ? $params['action'] : ''; 
    $empCls = new Employee($connString); 

    switch($action) { 
    case 'add': 
     $empCls->insertEmployee($params); 
    break; 
    case 'view': 
     $empCls->viewEmployee($params); 
    break; 
    case 'edit': 
     $empCls->updateEmployee($params); 
    break; 
    case 'delete': 
     $empCls->deleteEmployee($params); 
    break; 
    default: 
    $empCls->getEmployees($params); 
    return; 
    } 

    class Employee { 
    protected $conn; 
    protected $data = array(); 
    function __construct($connString) { 
     $this->conn = $connString; 
    } 

    public function getEmployees($params) { 

     $this->data = $this->getRecords($params); 

     echo json_encode($this->data); 
    } 
    function insertEmployee($params) { 
     $data = array();; 
     $sql = "INSERT INTO `employee` (employee_name, employee_salary, employee_age) VALUES('" . $params["name"] . "', '" . $params["salary"] . "','" . $params["age"] . "'); "; 

     echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data"); 

    } 


    function getRecords($params) { 
     $rp = isset($params['rowCount']) ? $params['rowCount'] : 10; 

     if (isset($params['current'])) { $page = $params['current']; } else { $page=1; }; 
     $start_from = ($page-1) * $rp; 

     $sql = $sqlRec = $sqlTot = $where = ''; 

     if(!empty($params['searchPhrase'])) { 
      $where .=" WHERE "; 
      $where .=" (employee_name LIKE '".$params['searchPhrase']."%' ";  
      $where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' "; 

      $where .=" OR employee_age LIKE '".$params['searchPhrase']."%')"; 
     } 
     if(!empty($params['sort'])) { 
      $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." "; 
     } 
     // getting total number records without any search 
     $sql = "SELECT * FROM `employee` "; 
     $sqlTot .= $sql; 
     $sqlRec .= $sql; 

     //concatenate search sql if value exist 
     if(isset($where) && $where != '') { 

      $sqlTot .= $where; 
      $sqlRec .= $where; 
     } 
     if ($rp!=-1) 
     $sqlRec .= " LIMIT ". $start_from .",".$rp; 


     $qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data"); 
     $queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data"); 

     while($row = mysqli_fetch_assoc($queryRecords)) { 
      $data[] = $row; 
     } 

     $json_data = array(
      "current"   => intval($params['current']), 
      "rowCount"   => 10,    
      "total" => intval($qtot->num_rows), 
      "rows"   => $data // total data array 
      ); 

     return $json_data; 
    } 
    function updateEmployee($params) { 
     $data = array(); 
     //print_R($_POST);die; 
     $sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."', employee_age='" . $params["edit_age"] . "' WHERE id='".$_POST["edit_id"]."'"; 

     echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data"); 
    } 

    function viewEmployee($params) { 
     $data = array(); 
     //print_R($_POST);die; 
     $sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'"; 

     echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data"); 
    } 

    function deleteEmployee($params) { 
     $data = array(); 
     //print_R($_POST);die; 
     $sql = "delete from `employee` WHERE id='".$params["id"]."'"; 

     echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data"); 
    } 
} 
?> 

我的查詢,查看的數據是:

function viewEmployee($params) { 
     $data = array(); 
     //print_R($_POST);die; 
     $sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'"; 

     echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data"); 
    } 

任何想法,我應該怎麼做才能選擇數據數據庫並以html格式打印它們?

+0

你知道,如果AJAX成功地執行? –

+0

是的,它工作正常,因爲編輯和刪除選項沒有問題。 – infocrasher

回答

0

如果您使用$_REQUEST中的錯誤變量名稱,那麼在使用時,您正在使用ìd,因爲它在窗體隱藏字段中進行了配置。

嘗試

function viewEmployee($params) { 
    $data = array(); 
    //print_R($_POST);die; 
    $sql = "Select employee_name FROM employee WHERE id='".$params["view_id"]."'"; 

    $result = mysqli_query($this->conn, $sql) or die("error to view employee data"); 
    echo json_encode($result->fetch_all(MYSQLI_ASSOC)); 
} 
+0

我現在做了,但仍然得到同樣的東西。我的查詢:$ sql =「Select employee_name FROM employee WHERE id ='」。$ params [「view_id」]。「'」;但看看我點擊查看按鈕時:http://www5.0zz0.com/2017/09/23/17/507700939.png http://www5.0zz0.com/2017/09/23/17/508670784我只能得到這個名字。 – infocrasher

+0

嗯,我認爲我的查詢不起作用,因爲我還沒有執行它,我從更新收集數據的代碼中複製代碼,點擊保存按鈕後,查詢將被執行。所以我的問題是:我如何執行選擇查詢並在該彈出窗口中打印數據。 ! 。 – infocrasher

+0

grid.find( 「命令視點 」)上(「 點擊」,函數(E) { 返回警報( '試驗'); \t \t \t \t \t })。端() – infocrasher