简体   繁体   中英

Multiple checkboxes inserting improperly

I've researched this for two days and just about have it working... trouble is, when I check TWO checkboxes on my dynamically populated form, I get FOUR records inserted. It gets weirder... ONE of the records is unique. THREE have the same information. I'm totally lost here.

Here is the code for the form:

<form name="form1" id="form1" method="post" action="insert_zip_codes.php?u=<?php echo $_SESSION['username'] ?>">
                            <table class="bordered" cellspacing="0">
                            <tr><th>City</th><th>State</th><th>ZIP Code</th></tr>
                            <?php while($row = mysql_fetch_array($rs)) { ?>
                                <tr><td><input name="zip_code[]" type="checkbox" id="zip_code" value="<?php echo $row[zip_code] ?>" /></td><td><?php echo $row[city] ?></td><td><?php echo $row[state] ?></td><td><?php echo $row[zip_code]?></td></tr> 
                            <?php } ?>
                            </table><br />
                              <input type="submit" name="Submit" value="Submit" />
          </form>

Here is the code for the insert statement on the next page.

<?php $u = $_GET['u']; ?>
<?php var_dump($_REQUEST); ?> </br> </br>`
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);
}  
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
} 

echo $query;  // print the sql to screen for de-bugging

$results = mysql_query($query); ?>

When I hit submit, the following prints out and it inserts successfully into the database.

 ["zip_code"]=> array(2) { [0]=> string(5) "97477" [1]=> string(5) "97478" }

Looks right, right? But then the database gets these records...

id  40  username  ***  zip_code  97478
id  41  username  ***  zip_code  97478
id  42  username  ***  zip_code  97478
id  43  username  ***  zip_code  97477

As you can see, the darned thing is entering the first zipcode checked on the page only once (as the fourth record) but is entering the SECOND zipcode first THREE TIMES.

Any idea why? I'm at a loss.

Thank you in advance!!! :)

You are calling mysql_query() 3 times, and with 2 of them outside your foreach() loop, it will insert the last $query / $zip_code an additional 2 times.

<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);  // 1st time (does query foreach zip_code)
}  
if(mysql_query($query)) // 2nd time (does query on last zip_code a second time)
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
} 

echo $query;  // print the sql to screen for de-bugging

$results = mysql_query($query); // 3rd time (does query on last zip_code a third time) ?>

Removing the last one, as it is just there for de-bugging, you could change your loop code to -

<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
$result = mysql_query($query);
if($result)
{
echo 'success ';
}
else
{
echo 'failure' .mysql_error();
} 
}

The problem relates to your use of mysql_query() and the $query variable you are using. Here's a walk through.

You submit two postcodes via $_POST You loop through the $_POST array and set $query to be the INSERT string. You then pass that into the function mysql_query() to execute the command to INSERT the record.

So now, you've got two records in your database. You didn't do any checks to see if they worked individually as inserts during that loop (you should have). You also didn't do any escaping to avoid dodgy injection tampering. (you should have).

Anyway, after your loop, this is where it all goes wrong. You then check to see if it worked by running mysql_query($query) again. This is actually going to run the last $query INSERT string you generated again as a command. So that inserts another record into the table.

THEN, you do something with the variable $results by yet again, running the mysql_query($query) command. So that's another record you've inserted. This means you would have 4 records inserted into your table.

A suggestion This is off the top of my head! - not tested it

$u = "Whatever";
$inserted = 0;
$fatal = Array();

foreach($_POST['zip_code'] AS $z){
    if(mysql_query("INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".mysql_real_escape_string($z)."')";
        $success += mysql_affected_rows();
    } else {
        $fatal[] = mysql_error();
    }
}

echo "Inserted $success of ".count($_POST[zip_code])." records.<br />";
if(count($fatal)){
    $fatal = array_unique($fatal); 
    echo "The following error(s) occurred:<br />";
    print "<pre>";
    print_r($fatal);
    print "</pre>";
}

Hope that helps in some way!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM