Problem with insert value in database with json_encode
I want insert on a row of database table, following value with following php code(foreach
) but after insert get following error, what do i do?
Values:
<div class="column">
<input type="text" name="start_date[1][]" value="1111">
<input type="text" name="end_date[1][]" value="1111">
<input type="text" name="price_change[1][]" value="1111">
</div>
<div class="column">
<input type="text" name="start_date[2][]" value="2222">
<input type="text" name="end_date[2][]" value="2222">
<input type="text" name="price_change[2][]" value="2222">
</div>
<div class="column">
<input type="text" name="start_date[3][]" value="3333">
<input type="text" name="end_date[3][]" value="3333">
<input type="text" name="price_change[3][]" value="3333">
</div>
Php code:
$residence_ups_input = $this->input->post('start_date');
$residence_upe_input = $this->input->post('end_date');
$residence_upc_input = $this->input->post('price_change');
var_dump($residence_ups_input); // output this is: nobool(false)
$residence_p = array();
开发者_如何学运维 foreach ($residence_ups_input as $idx => $name) { //line 134
$residence_p[] = array(
'start_date' => $residence_ups_input[$idx],
'end_date' => $residence_upe_input[$idx],
'price_change' => $residence_upc_input[$idx]
);
}
;
$data = array(
//'name' => $this -> input -> post('name'),
'residence_p' => json_encode($residence_p)
);
$this->db->insert('tour_foreign', $data);
Error:
A PHP Error was encountered
Severity: Warning Message: Invalid argument supplied for foreach() Filename: inser.php Line Number: 134
Change all columns:
<div class="column">
<input type="text" name="start_date[1][]" value="1111">
<input type="text" name="end_date[1][]" value="1111">
<input type="text" name="price_change[1][]" value="1111">
</div>
....
to:
<form method="post">
<div class="column">
<input type="text" name="start_date[]" value="1111">
<input type="text" name="end_date[]" value="1111">
<input type="text" name="price_change[]" value="1111">
</div>
....
</form>
replace
foreach ($residence_ups_input as $idx => $name) {
with
foreach (get_object_vars($residence_ups_input) as $idx => $name) {
you are passing an object to foreach, it wants an associative array. From now on do
json_decode($string, true)
instead of
json_decode($string)
and access the variable like this:
$var['key'];
instead of $var->key
the $residence_ups_input
variable is not an array
use this code :
array_push($residence_ups_input,$this->input->post('start_date'));
array_push($residence_upe_input,$this->input->post('end_date'));
array_push($residence_upc_input,$this->input->post('price_change'));
to get the values then use the foreach()
精彩评论