简体   繁体   中英

Foreach loop is not working correctly

I have this code and it does not insert the values in the database. What am I doing wrong?

while ($rij = mysql_fetch_assoc($doquery2))
{
    $user_id = $rij['id'];
}

$cat = $_POST['cat'];

foreach($cat as $key => $value) 
{
    //$sql = "";

    if ($value > 0) 
    {
        $sql = sprintf("INSERT INTO cat VALUES('','$user_id','%s');",$value);
        mysql_query($sql);
    }
}

In my form each checkbox is built as follow:

<input type="checkbox" name="cat[]" value="Lifestyle">

What am i doing wrong?

If I remember correctly, an unchecked value won't get passed through to $_POST at all. So you can just strip the lines checking $value. I think you might be running into issues there with different browsers sending different values for a checked box. So try this:

foreach($cat as $key => $value) 
{
    //$sql = "";

    $sql = sprintf("INSERT INTO cat VALUES('','$user_id','%s');",$value);
    mysql_query($sql);
}

You should log your sql statement and log any mysql_error().

Also your array will be a regular index based array so you should use (although this is probably not your source of error)

foreach($cat as $value) 

Where are you converting $_REQUEST['cat']/$_GET['cat']/$_POST['cat'] into $cat... You seem to be looping on an array called $cat but i think you are used to work with register_globals and your server doesn't support it anymore. Thats why it's not doing what you expect.

But i might be wrong...

You forgot include table columns also ; not required here

$sql = sprintf("INSERT INTO cat (id, user,category) VALUES('','$user_id','%s')",$value);

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