4

我正在尝试将 html 表行保存到 php 数组中,然后将数组保存在数据库中。

<form action="" method="post">
        <table class="widefat" id="theTable">
                        <thead>
                                <tr>
                                   <th>Level Identifier</th>
                                    <th>Non-logged in message</th>
                                    <th>Logged in message</th>
                                </tr>
                        </thead>
                        <tbody>

                                  <tr>
                                    <td><input type="text" value="" style="height: 19px;background-color: white;font-size:10px;"/></td>
                                    <td><textarea style="font-size:10px;" name="promo_msg_free" cols="43" rows="1">This is your custom message template</textarea></td>
                                    <td><textarea style="font-size:10px;" name="promo_msg_free" cols="43" rows="1">This is your custom message template</textarea></td>
                                  </tr>

                                   <tr>
                                    <td><input type="text" value="" style="height: 19px;background-color: white;font-size:10px;"/></td>
                                    <td><textarea style="font-size:10px;" name="promo_msg_free" cols="43" rows="1"></textarea></td>
                                    <td><textarea style="font-size:10px;" name="promo_msg_free" cols="43" rows="1"></textarea></td>
                                  </tr>

                        </tbody>    
                    </table> 
                </form>

如何检索每一行数据并将其保存到数组元素,最后我将数组保存到数据库?谢谢

4

2 回答 2

7

如果您想保存每一行的 HTML,请执行以下操作:

使用 jQuery。

var rowsArray = {};
var i = 0;
$('#theTable tr').each(function({
    rowsArray[i] = $(this).html(); // if you want to save the htmls of each row
    i++;
});

然后使用ajax发布这些数据

$.ajax({
   type: 'post',
   url: URL_TO_UR_SCRIPT,
   data: { myarray : rowsArray },
   success: function(result) {
     //ur success handler OPTIONAL
   }
});

在 PHP 方面,您可以:

$array = isset($_POST['myarray']) ? $_POST['myarray'] : false;
if ($array) { 
  $array = serialize($array);
  //UPDATE YOUR DATABASE WITH THIS SERIALIZED ARRAY
}

您不能将 php 数组保存到数据库中,因此您需要对其进行序列化,并且当您从数据库中检索它时使用unserialize ()

如果您的意思是要保存输入和文本区域的值,那么您需要为每个元素设置名称,然后使用 $_POST 在脚本中访问它们。

 $array = array;
 foreach($_POST as $key => $value) {
    //sanitize your input here
    $array[$key] = $value;
 }
 $serialized = serialize($array);
 //save serialized array in your DB

注意/提示: 仅供参考,不要使用 html 表格来布置表单元素。表应该用于数据表示。您可以使用divcss轻松地做同样的事情

于 2013-03-19T18:24:43.780 回答
0

这是基本的 PHP 用法。您提供输入名称,当您提交表单时,提交页面中的脚本将完成这项工作。

您的价值观将驻留在

$_POST 

大批。所以你通过

$_POST['input_name']

您必须通过调用其名称来遍历每个值,然后将其相应地放入数据库中。

于 2013-03-19T18:20:46.887 回答