将HTML表行转换为PHP数组并将其保存到数据库中?

Irf*_*fan 3 html php html-parsing php-parser

我正在尝试将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>
Run Code Online (Sandbox Code Playgroud)

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

GGi*_*Gio 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++;
});
Run Code Online (Sandbox Code Playgroud)

然后使用ajax发布此数据

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

在PHP方面你做:

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

你不能将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
Run Code Online (Sandbox Code Playgroud)

注意/提示: FYI不使用html表来布局表单元素.表应该用于数据表示.你可以使用div和css轻松做同样的事情