mysql - Foreach query insert in multiple rows PHP not working? -
i googled , tested can not below php script insert mysql database. when run query directly in mysql management tool insert works. want insert query multiple rows in table task_in
.
i tested database/table connection , ok, can please explain why php script not insert data in database table task_in
?
php script:
<?php if(isset($_post['tasks'])) { $tasks = $_post['tasks']; foreach ($tasks $task_list_id) { $sql = mysql_query("insert task_in (task_list_id, customer_id, user_id, created_at) values ('$task_list_id', '1', '1', now())"); print_r($task_list_id); } } ?>
part of form:
<td><input type="checkbox" name="tasks[][task_list_id]" value=<?php echo($key[0]);?>></td> <td><input type="checkbox" name="tasks[][task_list_id]" value=<?php echo($key[1]);?>></td> </tr> <td>nav.rep for</td>
the print_r in foreach loop returns this:
array ( [task_list_id] => 1 ) array ( [task_list_id] => 2 ) array ( [task_list_id] => 8 )
my table task_in looks this:
create table `task_in` ( `id` int(11) not null auto_increment, `task_id_unique` int(11) not null, `task_list_id` int(11) not null, `customer_id` int(11) not null, `user_id` int(11) not null, `created_at` datetime not null, primary key (`id`), key `tasklistid` (`task_list_id`), constraint `tasklistid` foreign key (`task_list_id`) references `task_list` (`id`) ) engine=innodb auto_increment=50 default charset=utf8;
ps. aware of sql injections in above code + pdo , mysqli , changed asap. please not comment on this.
update solved.
@axiac suggestions works , commented @fejese, table have foreign key taks_list_id expecting int , got string, , therefore returned following sql error:
invalid query: cannot add or update child row: foreign key constraint fails (workcard
.task_in
, constraint tasklistid
foreign key (task_list_id
) references task_list
(id
))
i added implode function php script , php script solved insert issue:
<?php if(isset($_post['tasks'])) { $tasks = $_post['tasks']; foreach ($tasks $task_list_id) { $values = implode('""', $task_list_id); $sql = mysql_query("insert task_in (task_list_id, customer_id, user_id, created_at) values ('$values', '1', '1', now())"); } if (!$sql) { die('invalid query: ' . mysql_error()); } } ?>
thank suggestion , comments.
your $task_list_id
array , should integer. change html this:
<input type="checkbox" name="tasks[]" ...>
and fix it.
Comments
Post a Comment