简体   繁体   English

如何编辑动态创建的表单文本框值并将其插入MySQL DB?

[英]How to edit and insert dynamicaly created form textboxes values to MySQL DB?

I'm having a bunch of features table in MySQL DB in my PHP project. 我的PHP项目中的MySQL DB中有一堆功能表。 I'm fetching through php and creating a table with textboxes named by column name and id of record in photos table using code: 我正在通过php抓取并创建一个带有文本框的表,该文本框通过使用代码的照片中的列名和记录ID命名:

functions.php Code: functions.php代码:

function m_html_editPhotos($id) {
$result = "<table class=\"tabelka\" id=\"tbl_photos\"><thead><tr><th>Miniaturka</th><th>Duże zdjęcie</th></tr></thead><tbody>";
$mysqli = m_db_Init();
$qry = "SELECT ID, Img_Min, Img_Nrm FROM tbl_Zdjecie WHERE ID_Grzyb = ?";
if($stmt = $mysqli -> prepare($qry)) {
          $stmt -> bind_param("i", $id);
          mysqli_stmt_bind_result($stmt, $img_id, $img_min, $img_nrm);
          $stmt->execute();
          $i =0;
          while (mysqli_stmt_fetch($stmt)) {
              $i = $i+1;
              $result .= "<tr><td><!--<label>Link do miniaturki:<label>--><input type=\"text\" class=\"required\" name=\"photo[$i][min]\" value=$img_min></td><td><!--<label>Link do zdjęcia pełnego rozmiaru:</label>--><input type=\"text\" class=\"required\" name=\"photo[$i][nrm]\" value=$img_nrm></td><td style=\"display:none;\"><input type=\"text\" name=\"photo[$i][id]\" value=$img_id /></td></tr>";
          }
          $stmt -> close();      
}
mysqli_close($mysqli);
$result .= "</tbody></table><div class=\"link\" onclick=\"AddPhotoEditRow();\">Dodaj kolejne zdjęcie</div>";
return $result;
}

Now what I'd like is to edit photos table iterating through each row of generated as above table with textboxes for thumbnail_url ( img_min ) and full size link ( img_nrm ) Additionally I'd like to add new ones to the table from dynamically created rows by function AddPhotoEditRow(); 现在,我要编辑的照片表格遍历上面生成的每一行,并带有thumbnail_url( img_min )和完整尺寸链接( img_nrm )的文本框通过功能AddPhotoEditRow();

functions.js Code: functions.js代码:

function AddPhotoEditRow(){
 $('#tbl_photos > tbody:last').append('<tr><td><input type="text" name="photo[0][min]"></td><td><input type="text" name="photo[0][nrm]"></td><td style=\"display:none;\"><input type=\"text\" name=\"photo[0][id]\" value=\"0\" /></td></tr>');
}

edit.php Code: edit.php代码:

include 'functions.php';
if(isset($_POST["change"])) m_db_updateAllFeatures($_GET["id"]);
if (m_db_isAdmin("")){
if (!isset($_GET["id"]) || !is_numeric($_GET["id"]))
    header("Location: ../index.php");
else {
if (isset($_POST["Nazwa_PL"]))
    m_db_UpdateName("PL", $_GET["id"],$_POST["Nazwa_PL"]);
if (isset($_POST["Nazwa_Lac"]))
    m_db_UpdateName("Lac", $_GET["id"],$_POST["Nazwa_Lac"]);
render_edit_body();
    }
}

I'd like to iterate somehow through photos links and update existing records by parsing textbox names passed through $_POST, additionally would be good to insert new photo links (that with id=0). 我想通过照片链接以某种方式进行迭代,并通过解析通过$ _POST传递的文本框名称来更新现有记录,此外,最好插入新的照片链接(id = 0)。 I'm setting new rows' id to 0 because I need to distinguish if I'm inserting to table, or updating, right? 我将新行的ID设置为0,因为我需要区分是插入表还是更新,对吗? I've assumed that all 0 -indexed fields should be added, rest of them should be inserted. 我假设应该添加所有0索引字段,其余的应该插入。 I might have my conception wrong, if there is a better way to do full functionality to that table "control" then I'm very open to suggestions. 我的想法可能是错误的,如果有更好的方法可以对表格“控件”执行全部功能,那么我很乐意提出建议。

You've got the basics, except 您已经掌握了基本知识,除了

$('#tbl_photo snip snip name="photo[0][min]"> snip snip snip
                                    ^---

the 0 should not be hardcoded. 0不应该被硬编码。 You're telling php to create an array of 'photo' values in the $_POST array, but then you force the index keys to be 0 for all entries, causing later ones to overwrite earlier ones. 您要告诉php在$ _POST数组中创建一个由'photo'值组成的数组,但是随后您将所有条目的索引键都强制为0,从而导致后面的条目覆盖以前的条目。

Keep a count in Javascript as to how many of these fields you've inserted, and use that count to increment the index key, eg 在Javascript中对已插入的这些字段中的多少进行计数,并使用该计数来递增索引键,例如

$('#tbl_photo snip snip name="photo[' + i + '][min]"> snip snip snip

instead, where i is the field count. 相反, i是字段数。 Then it's a simple matter of: 然后,这很简单:

foreach($_POST['photo'] as $i => $photo) {
    echo $photo['min'];
}

to get that min value for each photo field. 以获得每个光场的最小值。

If you use 0 for all newly created HTML elements, the PHP $_POST will contains just the information of the last item. 如果对所有新创建的HTML元素都使用0 ,则PHP $_POST将仅包含最后一项的信息。

This is my solution using the same approach as yours with a bit of modification, supposed that we have a form wrap outside out loop and an array named $data contains the seeding information: 这是使用相同的方法,你带着几分修改我的解决方案,假设我们有一个form包装外面退出循环和数组名为$data包含了播种的信息:

PHP code to create the table PHP代码创建表

// the $data array contains a list of picture object, these object will be updated later.
foreach($data as $num => $row)
{
    echo "<tr>\n";
    echo sprintf("<td><input type='text' name='name[%d]' value='%s' /></td>\n", $num, $row['name']);
    echo "</tr>\n";
}
echo "<tr><td>\n";
echo "<a id='add-item'>Add new item</a>\n";
echo "<input type="hidden" name='num-created' value='0' />";
echo "</td></tr>\n"

JavaScript code to add new element (using jQuery) JavaScript代码以添加新元素(使用jQuery)

$(document).ready(function(){
    $('#add-item').click(function(){
        var currentCreatedNum = $("input[name=num-created]").val() * 1;
        var html = "<tr>";
        html += "<td><input type='text' name='newname["+ (currentCreatedNum + 1) +"]' value='' /></td>";
        html += "</tr>";            
        $("input[name=num-created]").val(currentCreatedNum + 1);
    });
});

The PHP code to manipulate the POST request PHP代码来处理POST请求

# check contrains ...

# update old records
foreach($_POST['name'] as $id => $name)
{
    // get information of existing item and update this record

}

# create new record
foreach($_POST['newname'] as $order => $name)
{
    // get information of new item and create a new record

}

As you can see, the name attribute of manual created elements must be different from the existing one. 如您所见,手动创建的元素的name属性必须与现有元素不同。

If I'm understanding, you're wanting to access each dynamically created table item? 据我了解,您想访问每个动态创建的表项吗? You can do this by simply creating a dynamic array. 您可以通过简单地创建一个动态数组来做到这一点。 As each new TD element (or whatever element) is generated, make the name like name=Something[] (with empty brackets). 生成每个新的TD元素(或任何其他元素)时,请使用name=Something[]类的name=Something[] (带有空心括号)。 This will automatically assign each item generated as a member of the array called "Something". 这将自动将生成的每个项目分配为称为“ Something”的数组的成员。 You can of course generate key values through a counter as well. 当然,您也可以通过计数器生成键值。

Here's a simplified example from a project I did, where an "Update" button (not shown here) posts back to the same page: 这是我所做的项目的简化示例,其中的“更新”按钮(此处未显示)发回到同一页面:

echo "<td class='grid'>
<input type='checkbox' name='chkDel[]' />
</td>";

Then the PHP would be as follows: 然后,PHP将如下所示:

if (isset($_POST['chkDel'])) {

    // Make a MySQL Connection
    $con = mysql_connect(host,user,pwd) or die(mysql_error());
    mysql_select_db("db_name"); 

    $rows = 0;

    foreach($_POST['chkDel'] as $chkdel)  {

        //query to delete post
        $delQuery = "DELETE FROM table WHERE ".$chkdel;

        //run the query 
        mysql_query($delQuery) or die(mysql_error());

        //Get rows affected
        $i = mysql_affected_rows();
        $rows = $rows + $i;
    }

    mysql_close($con);
}

Is that what you're looking for? 那是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM