-->

转换HTML表行到PHP数组并把它保存到数据库? [关闭](Convert HTML table

2019-08-17 18:38发布

我想一个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>

我怎样才能检索到的每一行数据并将其保存到数组元素,最后我会保存数组分贝? 谢谢

Answer 1:

如果你想节省每一行HTML DO:

使用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做samething



Answer 2:

这是基本的PHP使用。 你给你输入名字,一个当您提交表单,你的脚本在提交的页面将做的工作。

你的价值观将驻留在

$_POST 

阵列。 因此,您可以通过访问它们

$_POST['input_name']

你将不得不通过调用它的名字要经过的每个值,然后把它放到数据库相应。



文章来源: Convert HTML table rows into PHP array and save it to database? [closed]