2016-10-21 50 views
0

我有一個動態表,可以內聯編輯或可以動態添加行。我希望能夠點擊保存按鈕來運行UPDATE查詢來更新數據庫。但我無法弄清楚如何。我真的堅持這一點,並會感謝任何幫助。單擊保存按鈕後更新數據庫

我的DB連接:

<?php 
$host="xxxxx"; 
$dbName="xxxxxxxx"; 
$dbUser="xxxx"; 
$dbPass="xxxxxxxxxxxxx"; 

$dbh = new PDO("sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass); 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC"; 
?> 

HTML/PHP:

<div id="users-contain" class="ui-widget"> 
<table id="html_master" class="ui-widget ui-widget-content"> 
<thead> 
    <tr class="ui-widget-header"> 
    <td>ID</td> 
    <td>Vendor</td> 
    <td>Buyer ID</td> 
    <td>POC Name</td> 
    <td>POC Email</td> 
    <td>POC Phone</td> 
    <td>Edit/Delete</td> 
    </tr> 
</thead> 
<tbody> 

<?php 
    foreach ($dbh->query($sql) as $rows){ 
    ?> 
    <tr> 
     <td class="mr_id" contenteditable="false"><?php echo intval ($rows['MR_ID'])?></td> 
     <td class="mr_name" contenteditable="false"><?php echo $rows['MR_Name']?></td> 
     <td class="buyer_id" contenteditable="false"><?php echo $rows['Buyer_ID']?></td> 
     <td class="poc_n" contenteditable="false"><?php echo $rows['MR_POC_N']?></td>  
     <td class="poc_e" contenteditable="false"><?php echo $rows['MR_POC_E']?></td> 
     <td class="poc_p" contenteditable="false"><?php echo $rows['MR_POC_P']?></td> 
     <td><input type="button" class="edit" name="edit" value="Edit"> 
     <input type="button" class="deactivate" name="deactivate" value="Deactivate"></td> 
    </tr> 
<?php 
    } 
?> 
</tbody> 

    <input type="button" class="create-user" value="Add Row"> 
    <input type="submit" value="Save Table" class="save"> 

</table> 
</div> 

    <input type="button" class="create-user" value="Add Row"> 
    <input type="submit" value="Save Table" class="save"> 

的JavaScript:

// ----- Deactivate/Activate Row ----- 

$(document).on("click", "#html_master .deactivate", function() { 
    var $this = $(this); 
    var $tr = $this.closest('tr'); 
    var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate'; 

    // ------ Confirmation box in order to deactivate/activate row ----- 
    if (confirm('Are you sure you want to ' + action + ' this entry?')) { 
    $tr.toggleClass('deactivated'); 
    $this.val(function (i, t) { 
     return t == 'Deactivate' ? 'Activate' : 'Deactivate'; 
    }); 
    } 
}); 

// ----- Edit Row ----- 

$(document).on("click", "#html_master .edit", function() { 
    var $this = $(this); 
    var tds = $this.closest('tr').find('td').not('.mr_id').filter(function() { 
    return $(this).find('.edit').length === 0; 
    }); 
    if ($this.val() === 'Edit') { 
    $this.val('Save'); 
    tds.prop('contenteditable', true); 
    } else { 
    var isValid = true; 
    var errors = ''; 
    $('#myDialogBox').empty(); 
    // changed from here....... 
    var elements = tds; 
    if (tds.find('input').length > 0) { 
     elements = tds.find('input'); 
    } 
    elements.each(function (index, element) { 
     var type = $(this).attr('class'); 
     var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text(); 
     // changed from here....... to here 
     // ----- Switch statement that provides validation ----- 
     switch (type) { 
     case "buyer_id": 
      if (!$.isNumeric(value)) { 
      isValid = false; 
      errors += "Please enter a valid Buyer ID\n"; 
      } 
      break; 
     case "poc_n": 
      if (value == value.match(/^[a-zA-Z\s]+$/)) { 
      break; 
      } 
      else { 
      isValid = false; 
      errors += "Please enter a valid Name\n"; 
      } 
      break; 
     case "poc_e": 
      if (value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) { 
      break; 
      } 
      else { 
      isValid = false; 
      errors += "Please enter a valid Email\n"; 
      } 
      break; 
     case "poc_p": 
      if (value == value.match('^[0-9()+/-]{10,}$')) { 
      break; 
      } 
      else { 
      isValid = false; 
      errors += "Please enter a valid Phone Number\n"; 
      } 
      break; 
     } 
    }) 
    if (isValid) { 
     $this.val('Edit'); 
     tds.prop('contenteditable', false); 
    } else { 
     alert(errors); 
    } 
    } 
}); 

// ----- Dialog Box ----- 

$(function() { 

    var dialog, form, 

     emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, 
     phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/, 
     mr_name = $("#mr_name"), 
     buyer_id = $("#buyer_id"), 
     poc_n = $("#poc_n"), 
     poc_e = $("#poc_e"), 
     poc_p = $("#poc_p"), 
     allFields = $([]).add(mr_name).add(buyer_id).add(poc_n).add(poc_e).add(poc_p), 
     tips = $(".validateTips"); 
    console.log(allFields); 

    function updateTips(t) { 
     tips 
     .text(t) 
     .addClass("ui-state-highlight"); 
     setTimeout(function() { 
     tips.removeClass("ui-state-highlight", 1500); 
     }, 500); 
    } 

    function checkRegexp(o, regexp, n) { 
     if (!(regexp.test(o.val()))) { 
     o.addClass("ui-state-error"); 
     updateTips(n); 
     return false; 
     } else { 
     return true; 
     } 
    } 

    function addVendor() { 
     var valid = true; 
     allFields.removeClass("ui-state-error"); 

     valid = valid && checkRegexp(mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name"); 
     valid = valid && checkRegexp(buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID"); 
     valid = valid && checkRegexp(poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name"); 
     valid = valid && checkRegexp(poc_e, emailRegex, "Please enter a valid email"); 
     valid = valid && checkRegexp(poc_p, phoneRegex, "Please enter a valid phone number"); 

     if (valid) { 
     var $tr = $("#html_master tbody tr").eq(0).clone(); 
     $.each(allFields, function(){ 
      $tr.find('.' + $(this).attr('id')).html($(this).val()); 
     }); 
     $tr.find('.mr_id').html($("#html_master tbody tr").length + 1); 
     $("#html_master tbody").append($tr); 
     dialog.dialog("close"); 
     } 
     return valid; 
    } 

    var dialog = $("#dialog-form").dialog({ 
     autoOpen: false, 
     height: 400, 
     width: 350, 
     modal: true, 
     buttons: { 
     "Add Row": addVendor, 
     Cancel: function() { 
      dialog.dialog("close"); 
     } 
     }, 
     close: function() { 
     form[ 0 ].reset(); 
     allFields.removeClass("ui-state-error"); 
     } 
    }); 

    form = dialog.find("form").on("submit", function(event) { 
     event.preventDefault(); 
     addVendor(); 
    }); 

    $(".create-user").button().on("click", function() { 
     dialog.dialog("open"); 
    }); 
    }); 


// ----- Save Table ----- 
$(document).on("click", ".save", function() { 

    // ------ Confirmation box in order to deactivate/activate row ----- 
    if (confirm('Saving will update the entire table. Are you sure you want to save?')) { 
     // yourformelement.submit(); 
    } else { 
     return false; 
    } 
}); 
+1

你應該做一個ajax調用併發布php文件中的表單數據並在那裏編寫代碼以更新表中的數據。 –

+1

你在哪個方面掙扎,即表單提交,ajax,更新查詢等?此外,有沒有什麼你已經嘗試過,沒有奏效? –

+0

http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax這是一個很好的例子 –

回答

0

在您的保存按鈕點擊事件,寫下面的代碼:

// ----- Save Table ----- 
$(document).on("click", ".save", function() { 

    // ------ Confirmation box in order to deactivate/activate row ----- 
    if (confirm('Saving will update the entire table. Are you sure you want to save?')) { 
    var tabledata=[]; 
    $("#html_master tbody tr").each(function(index) { 
     tabledata[index] = { 
      mr_id: $(this).find("td.mr_id").text(), 
      mr_name: $(this).find("td.mr_name").text(), 
      buyer_id: $(this).find("td.buyer_id").text() //add rest of the fields 
     }; 

}); 
    //now call a normal ajax request to your php process page 

    $.ajax({ 
     url: "process.php", 
     type: "post", 
     data: {data: tabledata}, 
     success: function(result){ 
      //do whatever you want 
     } 
    }) 

     // yourformelement.submit(); 
    } else { 
     return false; 
    } 
}); 

在你的PHP程序頁面(我假設process.php),你現在可以檢索這些數據後和運行SQL查詢

$data = $_POST['data']; 
foreach($data as $row){ 
    // now you have $row['mr_id'], $row['mr_name'] etc. do normal sql update query in each loop. I suppose mr_id is the primary key. so use it in where clause 
} 

這是拯救這整個表一次使用AJAX的總體思路。還請注意,我沒有測試代碼。可能有錯誤。雖然有一些豐富的第三方腳本,看起來不錯,使它更容易使用。

與單獨保存所有可能變慢的行相比,我認爲最好單獨保存每一行,因爲單擊編輯每行時已經有一個保存按鈕。在這種情況下,代碼需要修改一下。

希望它會有所幫助。讓我知道是否需要澄清!

+0

好吧......它是什麼樣的? process.php頁面? – Rataiczak24

+0

您可以在循環內執行正常的更新查詢,如下所示:$ sql =「UPDATE Stage_Rebate_Master SET MR_Name ='$ row [mr_name]',MR_POC_N ='$ row [poc_n]'WHERE MR_ID ='$ row [mr_id]'」 ; $ dbh-> query($ sql); –

+0

即時通訊非常確定我有一切,它的工作仍然..... .....我需要包括我的數據庫連接在process.php頁面? – Rataiczak24

相關問題