Jump to content

[SOLVED] Updating table row with checkbox array


mikenl

Recommended Posts

Hi,

 

I have a checkbox array that I use to update a table row.

 

Checkboxes look like:

 

name=lang[] value=1

name=lang[] value=2

(etc)

 

Table row looks like:

 

id, someid

lang1, 0

lang2, 1

lang3, 0

lang4, 0

lang5, 1

(etc)

 

MySQL query create by code should be: UPDATE language SET lang1 = '1', lang2 = '1', lang3 = '0' (etc) WHERE id = 'someid'

 

My code:

 

$language = $_POST['lang'];  // this is the checkbox array

$setlanguage = "UPDATE prof_language SET ";	

foreach ($language as $key => $value){
if(!empty($key)){
	$setlanguage = $setlanguage. ", ";
	}  
			if($value){
$setlanguage = $setlanguage. "lang".$key." = '1'";
} else {
$setlanguage = $setlanguage. "lang".$key." = '0'";
}
 }

$setlanguage = $setlanguage. " WHERE unid = '$session_id'";

mysql_query($setlanguage);

 

I have played with this for days but I can't get it to work. I need to update the row with new '1's and '0's...

Link to comment
Share on other sites

try

<?php
$language = $_POST['lang'];  // this is the checkbox array

$setlanguage = "UPDATE prof_language SET ";	
for ($i = 1; $i <= 5; $i++){
$out[] = "lang$i = '".(in_array($i, $language) ? 1 : 0)."'";
}
echo $setlanguage .= implode(', ', $out). " WHERE unid = '$session_id'";

mysql_query($setlanguage);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.