Please I need your help with grabbing rows from a table and dynamic text fields, then inserting it inti another table. I’m trying to do is grab some certain state_id from the table below, combine with data from <input type='text' name='constituency[]' /> text box displayed on the same page and then insert into table
+---------+--------------------------+
|state_id | state | senatorial |
|--- -----|----------|---------------|
| 1 | utah | A-North |
| 2 | utah | B-South |
+---------+----------+---------------+
The HTML i’m using to grab information. constituency is a dynamic text field and occur more than once so the need to have it in an array
<input type='hidden' name="state_id[]" value="<?php echo $row['state_id'];?>" />
<input type='text' name='constituency[]' />
Query I’m using to INSERT into table
<?php
$constituencys = $_POST['constituency'] ;
$state_id = $_POST['state_id'];
if(isses($_POST['constituency']))
{
$constituencys = $_POST['constituency'] ;
foreach($constituencys as $constituency) {
$state_id[$i]= $state_id[$i];
$query = mysql_query("
INSERT INTO `constituency` (
`constituency_id`,
`state_id`,
`constituency_name`
) VALUES (
NULL,
'".$state_id[$i]."',
'".$constituency."'
");
}
if(mysql_affected_rows()>0){
echo "Inserted Successfully";
}else{
echo "No Row Inserted";
echo mysql_error() ;
echo"<br>Error:".mysql_error();
echo"<br>Query:".$query;
} } ?>
Table I’m inserting to looks like this
+----------------+-------------+----------------------+
|constituency_id | state_id | constituency_name |
+----------------+----- -----+----------------------+
When I run the code “No Row Inserted”
is displayed on the screen
Please help me.
I most appreciate it, thank you.
ERROR SHOWN
Error: You have an error in your mysql syntax; check the manual that corresponds to your mysql server for the right syntax to use near " at line 2
Query:
Try this code first, update your post with results.
UPDATE
It looks like you may have ‘dirty’ input. Make sure you sanitize it for mysql before inserting it, by using mysql_real_escape_string. Try the following code.
NOTICE: At the end of your query, you’re missing a close parentheses. It has been added in the second example. Ensure it is there before you continue your tests.
Assuming that your HTML inputs are set up as an array correctly, this should work. It also tidies your code and helps with unwanted lag. Every millisecond counts. 🙂 If this doesn’t work, please post returned error and query again.