Andre
Andre

Reputation: 893

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?

Upvotes: 0

Views: 175

Answers (4)

Matt Stauffer
Matt Stauffer

Reputation: 2742

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);
}

Upvotes: 2

Vytautas
Vytautas

Reputation: 3539

You forgot include table columns also ; not required here

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

Upvotes: 0

Captain Giraffe
Captain Giraffe

Reputation: 14705

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) 

Upvotes: 1

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

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...

Upvotes: 0

Related Questions