2016-02-27 23 views
2

嗨我有一個從php生成的表,它是可編輯的,我想將編輯的值保存到數據庫。我不知道如何做到這一點,因爲頁面上有很多行(動態)。 這裏是一個屏幕截圖: - enter image description here從可編輯表使用php保存值

請建議

編輯: -

我的代碼是

echo "<table border='1'> 
<tr> 
<th>Sl Number</th> 
<th>Product Id</th> 
<th>Product Name</th> 
<th>Product Catagory</th> 
<th>Retal Price</th> 
<th>Max Price</th> 
<th>Min Price</th> 
<th>Initial Stock</th> 
<th>Quantity Sold</th> 
<th>Current Stock</th> 
<th>Last Order</th> 
<th>Edit/Update</th> 
</tr>"; 
while($row = $result->fetch_assoc()) 
{ 
     echo "<tr contenteditable>"; 
    echo "<td>" . $row["Row Number"]. "</td>"; 
    echo "<td>" . $row["Product Id"]. "</td>"; 
    echo "<td>" . $row["Product Name"]. "</td>"; 
    echo "<td>" . $row["Product Catagory"]. "</td>"; 
    echo "<td>" . $row["Retal Price"]. "</td>"; 
    echo "<td>" . $row["Max Price"]. "</td>"; 
    echo "<td>" . $row["Min Price"]."</td>"; 
    echo "<td>" . $row["Initial Stock"]."</td>"; 
    echo "<td>" . $row["Quantity Sold"]. "</td>"; 
    echo "<td>" . $row["Current Stock"]."</td>"; 
    echo "<td>" . $row["Last Order"]."</td>"; 
    echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>"; 
     echo "</tr>"; 
} 
+0

您的代碼在哪裏? – C2486

+0

是否允許用戶通過recors提交記錄或允許多個編輯? – AMartinNo1

+0

允許多次編輯,甚至可以在單擊按鈕中保存所有值(多行)。請建議 –

回答

3

讓我給你最好的方式 首先你的數據庫表中有空格:

$row["Initial Stock"]$row["Initial_Stock"]

那麼我會建議你使用AJAX,而不是浪費時間點擊按鈕

HTML頁面

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script> 
<script> 
$(function(){ 

    $("#loading").hide(); 
    //acknowledgement message 
    var message_status = $("#status"); 
    $("td[contenteditable=true]").blur(function(){ 
     var field_userid = $(this).attr("id") ; 
     var value = $(this).text() ; 



     $.post('update.php' , field_userid + "=" + value, function(data){ 



      if(data != '') 
      { 
       message_status.show(); 
       message_status.text(data); 
       //hide the message 
       setTimeout(function(){message_status.hide()},1000); 
      } 
     }); 
    }); 




}); 
</script> 


<style> 
table.zebra-style { 
    font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif; 
    text-align:left; 
    border:1px solid #ccc; 
    margin-bottom:25px; 
    width:100% 
} 
table.zebra-style th { 
    color: #444; 
    font-size: 13px; 
    font-weight: normal; 
    padding: 5px 4px; 

} 
table.zebra-style td { 
    color: #777; 
    padding: 4px; 
    font-size:13px; 

} 
table.zebra-style tr.odd { 
    background:#f2f2f2; 
} 


#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; } 
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; } 
</style> 

<div id="status"> </div> 
<div id="loading"></div> 





<table id="tableID" border="0" class="sortable table zebra-style"> 


<thead> 
    <tr> 
    <th>Sl Number</th> 
    <th>Product Id</th> 
    <th>Product Name</th> 
    <th>Product Catagory</th> 
    <th>Retal Price</th> 
    <th>Max Price</th> 
    <th>Min Price</th> 
    <th>Initial Stock</th> 
    <th>Quantity Sold</th> 
    <th>Current Stock</th> 
    <th>Last Order</th> 
    <th>Edit/Update</th> 
    </tr> 
</thead> 
<tbody class="list"> 
    <?php do { ?> 


    <tr> 
    <td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td> 
    <td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td> 
    <td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td> 
    <td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td> 
    <td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td> 
    <td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td> 
    <td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td> 
    <td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td> 
    <td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td> 
    <td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td> 
    <td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td> 
    <td contenteditable = 'false'></td>"; 



    </tr> 

    <?php } while($row = $result->fetch_assoc()) ?> 
</tbody> 
</table> 

,並且更新PHP頁面

<?php 


$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
        'username', 
        'password', 
        array(PDO::ATTR_EMULATE_PREPARES => false, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 


?> 

<?php 
if(!empty($_POST)) 
{ 
    //database settings 

    foreach($_POST as $field_name => $val) 
    { 
     //clean post values 
     $field_id = strip_tags(trim($field_name)); 

     //from the fieldname:user_id we need to get user_id 
     $split_data = explode(':', $field_id); 
     $product_id = $split_data[1]; 
     $field_name = $split_data[0]; 
     if(!empty($product_id) && !empty($field_name) && !empty($val)) 
     { 

      $affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id"); 
      echo $affected_rows; 

      echo "Updated"; 
     } else { 
      echo "Invalid Requests"; 
     } 
    } 
} 

else { 
    echo "Invalid Requests"; 
} 
?> 
+0

@trincot我相信不知道mysqli和PDO的事情。你會好心地編輯** php **部分中的代碼,我會看到在那裏使用的正確代碼,關於mysqli和PDO。我也在學習 –

+0

你可以在我的答案中查看一些建議的代碼。 – trincot

+0

@trincot現在我已經更新它作爲PDO兼容 –

2

你可以做的是與ID的PHP的Ajax調用你想要保存的行和新數據。然後使用PDO連接到數據庫並更新信息。完成之後,使用javascript編輯表格本身。

所以你需要做的是查找如何使用ajax調用和使用PDO。我建議當你回顯表本身 <button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td>其中行號是數據庫中的ID和updateRow()是您將創建的JavaScript函數,以獲取新信息並通過ajax發送它。不要使用mysql_ *,因爲它在PHP 7中不受支持,它很快就會死亡。代之以查找PDO。

4

要保存整個表格,你可以離開行級更新按鈕出來,有一個保存按鈕:

<button id="save">Save</button> 
<div id="msg"></div> 

味精區執行保存操作時,顯示從服務器反饋。

然後你想補充一點JavaScript來處理保存按鈕的點擊:

$('#save').click(function() { 
    var data = []; 
    $('td').each(function() { 
     var row = this.parentElement.rowIndex - 1; // excluding heading 
     while (row >= data.length) { 
      data.push([]); 
     } 
     data[row].push($(this).text()); 
    }); 
    $.post('savetable.php', {table: data}, function (msg) { 
     $('#msg').text(msg); 
    }); 
}); 

這將改變HTML表中的內容,沒有標題行,到JavaScript矩陣,然後被髮送到savetable .php進行處理。您可以使用$_POST['table']訪問該數組。當你實現這個時,首先調試,然後執行var_dump($_POST['table'])以確保數據正確傳輸,並且它具有您期望的數組結構。

然後遍歷該數組以將行插入到數據庫中。你可以使用mysqli或PDO來做到這一點。

PHP腳本savetable.php應該只能隨聲附和一個消息:一個確認(「表已成功保存」)或錯誤消息(「一個問題發生了你的數據沒有被保存。」)。

它不應該重現該表的HTML,因爲它已經顯示在瀏覽器中。任何PHP打印將被JavaScript代碼用於顯示在保存按鈕下方。

以下是savetable.php的樣子。但請仔細調試,我沒有測試這個代碼。在它工作之前,您首先需要設置您的數據庫模型當然是:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 
       'username', 'password'); 
// Configure that all database errors result in an exception: 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

try { 
    // Make a transaction: this allows to rollback any of the changes 
    // if anything goes wrong before the end of it. 
    $db->beginTransaction(); 
    // First delete all rows. 
    $db->exec("DELETE FROM mytable"); 
    // Prepare a statement that will be executed for each row. 
    // Needs to be extended for all columns: 
    $stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name) 
          VALUES (?, ?, ?)"); 

    foreach ($_POST('table'] as $row) { 
     $stmt->execute($row); // the columns are passed to the prepared statement. 
    } 
    // All went well: commit the changes. 
    $db->commit(); 
    echo "Table saved successfully"; 
} catch(PDOException $e) { 
    // Something went wrong: roll back any changes made 
    $db->rollback(); 
    echo "An error occurred: " . $e->getMessage(); 
} 
+0

「savetable.php」如何看起來像 –

+0

這看起來很危險。你刪除一切,然後再次插入。或者這就是PDO的工作方式 –

+1

我在我的代碼中解釋過,如果所有的工作都完成,任何更改都將完成。所以這是全部或沒有。這就是爲什麼打開了一個交易。所以如果INSERT失敗,DELETE的效果將被回調調用自動恢復。這不是專用於PDO,而是專用於SQL數據庫。通過這種方式,您無需使用單獨的DELETE,UPDATE和INSERT代碼來模擬網頁中的行刪除,插入和更新。 – trincot