Codeginiter retriveing values of checked checkbox - php

Im developing form application. Inside the form there are textboxes,textarea, checkboxes checkboxes are populated according to array. and i pass all the form values to controller . Values of textboxes, texarea print correctly. Problem is there only prints last value of checked checkbox. how do i print all checked box values. please help me & please find the code i used.
askQuestion.php (view)
<?php echo form_open('homepage/test'); ?>
<p>
<div>
<div class="form-group">
Question Title:<br/>
<input type="text" value="" name="">
</p>
<div>
<div class="form-group">
<p>
Description: <br/>
<textarea name="decription" rows="5" cols="100"> </textarea>
</p>
<?php
$chk_group =array('1' => 'red',
'2' => 'aa',
'3' => 'bb',
'4' => 'cc',
'5' => 'dd'
);
var_dump($chk_group);
for ($i=1 ; $i<=count($chk_group);$i++)
{
$val =$chk_group[$i];
echo "<br>";
echo '<input type="checkbox" value="' . $val . '" name="chk_group">' . $val;
echo "</br>";
}
?>
</div>
<div class="form-group">
Declare new Tags:<br/>
<input type="text" value="" name="tag">
</p>
</div>
<p>
<input type="submit" class="btn btn-success btn-block" value="Post Your Question" id="postQuestion">
</p>
<?php echo form_close();?>
homepage.php (controller)
public function test() {
echo "test";
$name = $this->input->post('tag');
print_r($name);
$des = $this->input->post('decription');
print_r($des);
$data = $this->input->post('chk_group');
var_dump($data);
/* foreach ($this->input->post('chk_group') as $r) {
echo $r;
}
*/
}

You should use array to name the check boxes. You used loop to generate the check boxes & used same name for all. For this you got only last one value.
echo '<input type="checkbox" value="' . $val . '" name="chk_group[]">' . $val;

Related

Get checked or not checked multi value checkbox

Hi everyone I have a form with 5 checkboxes, once I run the post I would like to have all the checkboxes with the current status.
Example:
checkbox 1: on
checkbox 2: off
checbox 3: on
checkbox 4: off
checkbox 5: off
This is my code but it doesn't work with non-on states
<?php
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[]"><label>Mon</label>
<input type="checkbox" name="check_list[]"><label>Tue</label>
<input type="checkbox" name="check_list[]"><label>Wed</label>
<input type="checkbox" name="check_list[]"><label>Thu</label>
<input type="checkbox" name="check_list[]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>
How can I get all the checkboxes with the statuses sent in the post?
Thank You
The value keyword can be used to specify the value:
Hardcoded Values
$days = ['mon', 'tue', 'wed', 'thu', 'fri'];
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
foreach ($days as $day){
$isChecked = in_array($day, $array);
echo $day . ' is ' . ($isChecked ? ' checked' : ' not checked') . '<br />';
}
}
?>
<form action="" method="post">
<?php
foreach ($days as $day){
echo '<input type="checkbox" name="check_list[]" value="' .$day.'"><label>'.$day.'</label>';
}
?>
<input type="submit" name="submit" Value="Submit"/>
</form>
Dynamic Values
If the fields get added dynamically, hidden inputs can be used. The following snippet adds a hidden input for every available option. These hidden inputs can then be used to determine if there is an associated checkbox, and thus get the value.
Checkout the following example:
<?php
if(isset($_POST['submit'])){
$options = $_POST["check_list_options"];
$checkedValues = $_POST["check_list_values"];
foreach ($options as $optionId){
$isChecked = array_key_exists($optionId, $checkedValues);
if($isChecked){
echo 'option ' . $optionId . ' is checked and has value: '.$checkedValues[$optionId].'<br />';
}else{
echo 'option ' . $optionId . ' is not checked<br />';
}
}
}
?>
<form action="" id="checklist_form" method="post">
<div class="results">
</div>
<button type="button" id="add_days">
Add days
</button>
<input type="submit" name="submit" Value="Submit"/>
</form>
<script>
var addDays = document.querySelector('#add_days');
var form = document.querySelector('#checklist_form');
var results = document.querySelector('.results');
addDays.addEventListener('click', function(){
var inputId = document.querySelectorAll('.input').length;
results.innerHTML += '<input type="hidden" name="check_list_options[]" value="'+inputId+'" />' +
'<input type="checkbox" name="check_list_values['+inputId+']" value="mon'+inputId+'" class="input" />' +
'<label>Day '+inputId+'</label>' +
'<br />';
})
</script>
You can do this by giving a name to each checkbox or by adding the key to the name of checkbox, and create an array that contains the name of each checkbox, then check in a loop if the equivalent checkbox is set:
$checkboxes = ['checkbox 1', 'checkbox 2', 'checkbox 3', 'checkbox 4', 'checkbox 5'];
if(isset($_POST['submit'])){
foreach($checkboxes as $key=>$value) {
echo $value.': ';
if(isset($_POST["check_list"][$key])) echo 'on '; else echo 'off ';
}
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[0]"><label>Mon</label>
<input type="checkbox" name="check_list[1]"><label>Tue</label>
<input type="checkbox" name="check_list[2]"><label>Wed</label>
<input type="checkbox" name="check_list[3]"><label>Thu</label>
<input type="checkbox" name="check_list[4]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>

I want to calculate total price of subjects given and store it in database

I have no idea how to calculate total price of this subjects using php.
help me with it.
<div id="mydiv" style="display:none">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
<div id="mydiv1" style="display:none">
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
I want to calculate price total of this checkboxes and store it in database with its names using php
php part
if(isset($_POST['subject']))
{
$classes=$_POST['subject'];
$prices = array(
'biology' => 60,
'physics' => 200
);
$sum = array();
$getkeys = array_keys($_POST);
foreach($prices as $key => $value)
{
if(in_array($key, $getkeys)) $sum[] = $value;
}
$ar=array_sum($sum);
echo $ar;
if($classes)
{
$subject = implode(',', $ar);
$query="INSERT INTO feedetails (subjects,price) VALUES ('".$subject."','".$price."')";
if(mysqli_query($conn,$query))
{
echo ("<SCRIPT LANGUAGE='Javascript'>
window.alert('Your fee has been updated.Please proceed to pay.');
window.location.href='payment.php';
</SCRIPT>");
}
}
It appears that your summing strategy was not working, there were numerous issues there including this:
$getkeys = array_keys($_POST);
which appears as an attempt to get the subjects submitted, however they are in their own sub-array of $_POST, i.e. $_POST['subject']
This gets you the summing of the price information you require, however you will need to test your database INSERT code and debug this to ensure you are storing the data required correctly.
if (!empty($_POST['subject'])) {
$prices = [
'biology' => 60,
'physics' => 200,
'maths' => 300,
'science' => 400,
];
$sum = 0;
foreach ($_POST['subject'] as $subject) {
if (!empty($prices[$subject])) {
$sum += $prices[$subject];
}
}
echo '<pre>';
echo '$sum ' . print_r($sum, true);
echo '</pre>';
exit;
// process database inserts here
}
Additionally, when testing your code I notice you had hidden the checkboxes, to resolve this, use the following:
<div id="mydiv">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
Try This may be help:
I am not doing all code just you asked for sum part.
Rest you can do Ask if any confusion.
HTML
<form method='post'>
<div id="mydiv" >
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="social">social<br>
<input type="checkbox" name="subject[]" value="ssc">ssc<br>
<input type="submit" value="Calculate" name="submit"
class="wpcf7-
submit">
</div>
PHP
<?php
$classes =$_POST['subject'];
$prices = array('biology' => 60,'physics' =>
200,'maths'=>100,'ssc'=>40,'social'=>150);
$sum = 0;
echo 'Subject::Price<hr/>';
foreach($classes as $key=>$sub){
if(array_key_exists($sub,$prices)){
echo $sub.'::'.$prices[$sub]."<br />";
$sum = $sum+$prices[$sub];
}
}
echo '<hr/>';
echo $sum;
?>
OUTPUT

I need to write a program for my class will keep score of a bowling game

I need to write a PHP program that will keep score of a bowling game. I can handle the calculation of the scores that is not the problem. My problem is getting the data into arrays in the first place.
My idea is to have an array for each player like below:
$scores = array(
array(
'name' => 'Player 1',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
array(
'name' => 'Player 2',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
);
I wanted to have an initial form where you can enter the player names, this then creates the arrays and afterwards create another form for each player (array) to enter the scores.
What would be the best way to go about doing this?
Thanks
Edit: Will this work?
<input maxlength="30" name="players[1][player1]" size="30" type="text" />
<input maxlength="30" name="players[2][player2]" size="30" type="text" />
So the first form as show above will create the arrays and the the player name value. The second form like the below would add the scores, although I cant seem to get this to work.
<input maxlength="30" name="players[1][score]" size="30" type="text" />
<input maxlength="30" name="players[2][score]" size="30" type="text" />
Here is a small example. Perhaps buggy but it should work (for inspiration)
<h1>Bowling</h1>
<?php
if ( isset ( $_POST['next'] ) ) {
if ( isset ( $_POST['players'] ) ) {
$exp = explode("\n", trim($_POST['players']));
echo "<h2>Input Score</h2>";
echo '<form method="post" action="bowling.php">';
foreach ( $exp as $p ) {
if ( trim($p) != '') {
$name = trim(htmlspecialchars($p));
echo '<fieldset>';
echo '<label><h3>Input "' .$name.'" score</h3></label>';
echo '<input style="width:100%" type="text" name="score[]" placeholder="Put in the score for ' . $name . '. Just for example 1 2 3 4 5">';
echo '<input type="hidden" name="player[]" value="'.$name.'">';
echo '</fieldset>';
}
}
echo '<input type="submit" name="next" value="Results">';
echo '</form>';
}
if ( isset($_POST['score'], $_POST['player']) ) {
echo "<h2>Results</h2>";
$i = 0;
$result = [];
foreach ( $_POST['player'] as $name ) {
$result[$name] = $_POST['score'][$i];
$i++;
}
var_dump($result);
}
} else {
?>
<form method="post" action="bowling.php">
<textarea style="width:500px; height:500px;" name="players" placeholder="One player in each line and everything will be fine"></textarea>
<input name="next" type="submit">
</form>
<?php
} ?>

How to get form input array into PHP array but not empty field

I have a form like the one below which is posted to same page, and the user can dynamically add more textbox with jquery.
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
everything work fine but if someone add more textbox and leave some textbox as empty then it going to submit. this is my problem i don't want to submit empty textboxes in my table and i want server side solution for this.
Here is my full code with php
<body>
<?php
if ( isset($_POST['submit_order']) ) {
if ( !empty($_POST['Product']) && !empty($_POST['Quantity']) ) {
$product = ($_POST['Product']);
$quantity = ($_POST['Quantity']);
foreach ($product as $id => $value) {
$products = ($product[$id]);
$quantitys = ($quantity[$id]);
$query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection);
}
}
echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>";
mysql_close();
}
?>
<?php
if (!isset($_POST['submit_order'])) {
?>
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
<?php }
?>
</body>
You can use array_filter to get the elements of the arrays that are not empty. If the number of non-empty elements is different from the original array sizes, the user left some fields blank.
$filled_product = array_filter($product);
$filled_quantity = array_filter($quantity);
if (count($filled_product) < count($product) || count($filled_quantity) < count($quantity)) {
// Report error because of unfilled fields
}
Something like this should work:
foreach ($_POST[Product] as $key => $value):
if (empty($value)):
unset($_POST[Product][$key]);
endif;
endforeach;
foreach ($_POST[Quantity] as $key => $value):
if (empty($value)):
unset($_POST[Quantity][$key]);
endif;
endforeach;
Thank you everyone for helping me, unfortunately no one give me a complete solution for this question
but #Wranorn give me a idea and i change my code and yes this solve my question
here is my solution for this
<body>
<?php
if ( isset($_POST['submit_order']) ) {
$product = ($_POST['Product']);
$quantity = ($_POST['Quantity']);
foreach ($product as $id => $value) {
$products = ($product[$id]);
$quantitys = ($quantity[$id]);
if (!empty($products) && !empty($quantitys)) {
$query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection);
}
}
echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>";
mysql_close();
}
?>
<?php
if (!isset($_POST['submit_order'])) {
?>
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
<?php }
?>
</body>

PHP/MySQL throwing me index error but it's already listed

PHP it's throwing at me
Notice: Undefined index: username in D:\xampp\htdocs\0100348514\pages\account.php on line 16
Warning: mysql_query() expects parameter 1 to be string, resource given in D:\xampp\htdocs\pages\account.php on line 19
But in my database I have it exactly the same 'username' but it's still throwing it at me any ideas?
Code on that page
<?php
$page = "My Account";
session_start();
include '../includes/config.php';
?>
<div id="searchbar">
<form action="search.php" method="get">
<input type="text" name="search" />
<input type="submit" name="submit" class="btn btn-primary" value="Search" />
</form>
</div>
</div>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM login WHERE username = '$username'";
$result = mysql_query($con, $sql) or die(mysql_error($con)); //run the query
$row = mysql_fetch_array($result);
?>
<div id="wrapper">
<section id="content" class="shadow">
<div id="titlebar">
<?php
echo $page = '<h1> My ACCOUNT </h1>';
?>
</div>
<br />
<?php
//user messages
if(isset($_SESSION['error'])) //if session error is set
{
echo '<div class="error">';
echo '<p class="center">' . $_SESSION['error'] . '</p>'; //display error message
echo '</div><br />';
unset($_SESSION['error']); //unset session error
}
elseif(isset($_SESSION['success'])) //if session success is set
{
echo '<div class="success">';
echo '<p class="center">' . $_SESSION['success'] . '</p>'; //display success message
echo '</div><br />';
unset($_SESSION['success']); //unset session success
}
?>
<div id='left'>
<form id="registration" form action="accountprocessing.php" method="post">
<br />
<fieldset><h1>Update Your Details</h1><br />
<ol>
<li>
<label>Username*</label> <input type="text" name="username" required value="<?php echo $row['username'] ?>" readonly />
</li>
<?php
//generate drop-down list for state using enum data type and values from database
$tableName='member';
$colState='state';
function getEnumState($tableName, $colState)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colState'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumState('member', 'state');
echo '<select name="state">';
if((is_null($row['state'])) || (empty($row['state']))) //if the state field is NULL or empty
{
echo "<option value=''>Please select</option>"; //display the 'Please select' message
}
else
{
echo "<option value=" . $row['state'] . ">" . $row['state'] .
"</option>"; //display the selected enum value
}
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>'; //remove the quotes from the enum values
}
echo '</select><br />';
?>
</li>
<p> </p>
<li>
<label>Postcode*</label> <input type="text" name="postcode" required value="<?php echo $row['postcode'] ?>"/>
</li><br />
<li>
<label>Country*</label> <input type="text" name="country" required value="<?php echo $row['country'] ?>"/>
</li><br />
<li>
<label>Phone</label> <input type="text" name="phone" value="<?php echo $row['phone'] ?>"/>
</li><br />
<li>
<label>Mobile</label> <input type="text" name="mobile" value="<?php echo $row['mobile'] ?>" />
</li><br />
<li>
<label>Email*</label> <input type="email" name="email" required value="<?php echo $row['email'] ?>" />
</li><br />
<li><label>Gender*</label>
<?php
//generate drop-down list for gender using enum data type and values from database
$tableName='member';
$colGender='gender';
function getEnumGender($tableName, $colGender)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colGender'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumGender('member', 'gender');
echo '<select name="gender">';
echo "<option value=" . $row['gender'] . ">" . $row['gender'] .
"</option>"; //display the selected enum value
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>';
}
echo '</select>';
?>
</li>
</ol>
</fieldset>
<br />
<fieldset>
<p>Subscribe to weekly email newsletter?</p><br />
<label>Yes</label><input type="radio" name="newsletter" value="Y" <?php if($row['newsletter'] == "Y"){echo "checked";} ?>><br />
<label>No</label><input type="radio" name="newsletter" value="N" <?php if($row['newsletter'] == "N"){echo "checked";} ?>>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
</fieldset><br />
<p class="center"><input type="submit" name="accountupdate" value="Update Account" /></p><br />
</form>
</div>
<br />
<div id='right'>
<form id="registration" form action="accountimageprocessing.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<fieldset><h1>Update Image</h1><br />
<?php
if((is_null($row['image'])) || (empty($row['image']))) //if the photo field is NULL or empty
{
echo "<p class='center'><img src='../images/members/member.png' width=150 height=150 alt='default photo' /></p>"; //display the default photo
}
else
{
echo "<p class='center'><img src='../images/members/" . ($row['image']) . "'" . 'width=150 height=150 alt="contact photo"' . "/></p><br />"; //display the contact photo
}
?>
<label>New Image</label> <input type="file" name="image" />
<br />
<p>Accepted files are JPG, GIF or PNG. Maximum size is 500kb.</p>
<br />
<p class='center'><input type="submit" name="imageupdate" value="Update Image" /></p>
</form>
<br />
<br />
<form action="accountpasswordprocessing.php" method="post">
<h1>Update Password</h1>
<br />
<p>Passwords must have a minimum of 8 characters.</p> <br />
<label>New Password*</label> <input type="password" name="password" pattern=".{8,}" title= "Password must be 8 characters or more" required />
<br />
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<p class='center'><input type="submit" name="passwordupdate" value="Update Password" /></p>
<br />
</form>
<h1>Delete My Account</h1>
<br />
<p>We're sorry to hear you'd like to delete your account. By clicking the button below you will permanently delete your account.</p>
<br />
<form action="accountdelete.php" method="post">
<p class='center'><input type="submit" value="Delete My Account" onclick="return confirm('Are you sure you wish to permanently delete your account?');" ></p>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>"><br />
</fieldset>
</form>
</div>
</section> <!-- end #content -->
<div id="footernav" class id="shadow">
<?php
require "../inc/footer.php";
?>
</div>
</div>
Your mysql_query parameteres are reversed. It should be:
mysql_query($sql, $con);
Also as you can see in the linked PHP Manual page, this extension is deprecated and alternatives should be used:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_query()
PDO::query()

Categories