问题
I'm trying to save a html table rows into php array and then save the array in database.
<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>
How can i retrieve each row data and save it to array element and finally I would be saving the array to db? Thanks
回答1:
IF YOU WANT TO SAVE HTML OF EACH ROW DO:
Use 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++;
});
then use ajax to post this data
$.ajax({
type: 'post',
url: URL_TO_UR_SCRIPT,
data: { myarray : rowsArray },
success: function(result) {
//ur success handler OPTIONAL
}
});
In PHP side you do:
$array = isset($_POST['myarray']) ? $_POST['myarray'] : false;
if ($array) {
$array = serialize($array);
//UPDATE YOUR DATABASE WITH THIS SERIALIZED ARRAY
}
you cant save php array into database therefore you need to serialize it and when you retrieve it from DB use unserialize()
IF you meant that you wanted to save the input and text area values then you need to set the names for each of the element and then access them in your script using $_POST.
$array = array;
foreach($_POST as $key => $value) {
//sanitize your input here
$array[$key] = $value;
}
$serialized = serialize($array);
//save serialized array in your DB
NOTE/HINT: FYI do not use html table to lay out the form elements. Tables should be used for data representation. You could easily do samething using divs and css
回答2:
This is basic PHP usage. You give your inputs names, an when you submit your form, your script in the submitted page will do the job.
Your values will reside in the
$_POST
array. So you access them by
$_POST['input_name']
you will have to go through each value by calling its name and then put it in the database accordingly.
来源:https://stackoverflow.com/questions/15507368/convert-html-table-rows-into-php-array-and-save-it-to-database