insert values from checkboxes to database

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

cipher143
New php-forum User
New php-forum User
Posts: 3
Joined: Wed Feb 20, 2013 1:52 pm

insert values from checkboxes to database

Postby cipher143 » Sat Mar 09, 2013 10:36 am

how to insert multiple values from checkboxes?
how can i do that?
help me with a small example if possible so that i can nderstand well,plzzz.
Thank you!

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: insert values from checkboxes to database

Postby seandisanti » Mon Mar 11, 2013 8:28 am

checkboxes are only transmitted in request data when they're checked. so if you have a checkbox named 'check1', the page handling the form could just check for isset($_POST['check1']) and update accordingly. Here's an example of creating a dynamic update statement based on variable form input that I used on a project recently. for this example, the array '$toWrite' is the result of an array merge of the original values, and the fields populated on the form submission. I then removed all keys that weren't on the form to prevent the ability of someone to update fields that weren't on the form. The sample included happens after all of that.

Code: Select all



    $sql 
"UPDATE client SET ";
    foreach (
$toWrite as $key=>$value){
        
$sql .= $key "=" . ((is_numeric($value))?$value:$db->quote($value)) . ",";//quotes non numeric 
    
}
    
$sql=  rtrim($sql,',');//removes trailing comma generated on last record
    
$sql .= " WHERE id=".$_SESSION['client']->id;//adds where statement
    
$result=$db->query($sql);
    if (!
$result){
        die(
'update failed');
    }
    
$ref $_SERVER['HTTP_REFERER'];
    
$_SESSION['client']=  Client::findFromId($_SESSION['client']->id);
    
header('Location:'.dropGet($ref));//dropGet is a custom function to strip out get variables for the redirect
    
 

cipher143
New php-forum User
New php-forum User
Posts: 3
Joined: Wed Feb 20, 2013 1:52 pm

Re: insert values from checkboxes to database

Postby cipher143 » Tue Mar 12, 2013 5:52 am

Thank u!! :)

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: insert values from checkboxes to database

Postby seandisanti » Tue Mar 12, 2013 7:55 am

no problem, glad to help.


Return to “PHP coding => General”

Who is online

Users browsing this forum: Baidu [Spider], Bing [Bot], landi and 2 guests