Reputation: 544
I have three check box and three input field something like this,
<input type="checkbox" name="fruit" value="orange" >
<input type="text" name="orange" >Orange
<input type="checkbox" name="fruit" value="apple" >
<input type="text" name="n" >Apple<br/>
<input type="checkbox" name="fruit" value="mango" >
<input type="text" name="mango" >Mango
I have a mysql table named fruits with four column named id, apple, orange, mango. I want to do something like if user select orange , apple , mango (checkboxes) I want to insert data into orange , apple , mango in the table from the three input field , or if user select two user check box it will just insert data into two columns from the input field's value, or if just one check box is selected then insert into one column! what is the standard procedure to do that? Thanks in advance
Upvotes: 0
Views: 1330
Reputation: 27082
Only checked checkboxes are sent, so use isset
:
if (isset($_POST['mango']) || isset($_POST['apple']) || isset($_POST['orange'])) {
$query = 'INSERT INTO table VALUES (orange, apple, mango) VALUES (';
$query .= (isset($_POST['orange']) ? 1 : '') . ',';
$query .= (isset($_POST['apple']) ? 1 : '') . ',';
$query .= (isset($_POST['mango']) ? 1 : '');
$query .= ')';
}
Upvotes: 2
Reputation: 462
It worked for me.
My Code:
HTML
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="checkbox" name="fruit[]" value="orange" >Orange
<input type="checkbox" name="fruit[]" value="apple" >Apple
<input type="checkbox" name="fruit[]" value="mango" >Mango
<input type="submit" value="Insert into Database">
</form>
PHP
<?php
// define variables and set to empty values
$fruits = array();
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$fruits = test_input($_POST);
}
function test_input($data)
{
$servername = "";// localhost, server name
$username = "";// username
$password = "";//password
$dbname = "";//database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
for($i =0; $i < sizeof($data["fruit"]); $i++)
{
//select query where count > 0 and fruitname = $data["fruit"]
//If its first time, Select query returns false
// write Insert into db table values(fruitname = $data["fruit"] , count =1)
// if its exist value, select query returns count value,
// update query set value = value+ 1 where fruitname = $data["fruit"]
}
}
?>
Upvotes: 0