0
votes

so im trying to store values from a checkbox into my database It works if I use a normal Textbox but as soon as I attempt it with a checkbox it doesnt work any idea? I want to have two for example checkbox1 and checkbox2 there values should be stored in my database colums for example Colum1 colum2. Thanks in advance for anyhelp

<form name="checkbox.php" id="names" action="<?php echo JURI::current(); ?>" method="post">

<p><input type="checkbox" name="game" value="ExampleGame" />b</p>
<p><input type="checkbox" name="Age" value="ExampleAge" />b</p>

<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>

</form>

<?
if( (isset($_POST['game'])) || (isset($_POST['Age'])) ) {
//first name or last name set, continue-->

$game = $_POST['game'];
$Age= $_POST['Age'];

$db =& JFactory::getDBO();

$query = "INSERT INTO `gameTable` (`game`, `Age`)
VALUES ($game, $age);";
$db->setQuery( $query );
$db->query();

} else {
echo '<h4>One Field Is Required!</h4>';
}

?>
4
Can you provide the table definition? - Turophile
I think your above code will work only if both the checkboxes are checked. Since this won't always be the case you need to change your lines of $game = $_POST['game']; to something like $game = isset($_POST['game'])?$_POST['game']:0; - AyB
post your table definition - Ravi
My table is 3 fields, game_ID Type int Auto_Increment game type Varchar age type varchar - user3403327
Found it works whenever I have the Value set to an integer eg, <p><input type="checkbox" name="game" value="11" />b</p> - user3403327

4 Answers

0
votes

Try this

$query =  "INSERT INTO `gameTable` (`game`, `Age`) VALUES ('".$game."','".$age."', )";
0
votes

Check the values that come back from your form:

 $game = $_POST['game'];
 $Age= $_POST['Age'];

You should find that if the checkbox isn't selected, no value (in fact, no field) is returned. That may be your problem.

0
votes

Use some alerts for troubleshooting:

echo $_POST['game']; echo $_POST['Age']; echo $_POST['query'];

Even when you don't know what you are doing/doing wrong, try to troubleshoot the problem. Alerts help alot in PHP to check if you get the values on your variables that you expect.

If you get your query string, test this directly on your database.

0
votes

I resolve with this easy way:

<input type="checkbox" name="field_name" value="N" style="display: none;" checked />

On mysql database i have create a trigger

 if new.field_name= '' then set new.field_name= 'S';