I'm trying to add tick boxes and when the boxes are ticked a value adds up (a variable) that variable is then added into the database along with each checkbox once the form is submitted, I've been trying to modifiy this code but cant figure out how to not use the parseInt() function and output a single variable that I can then add into the database/Email reply to the customer. I'm really stuck and would appreciate some help.
(the options are suppose to actually be (deodoriser,carpet,carpetrepair,furniture,tabs,urine but im using demo options for now below in the insert staement they are the correct names)
This is my HTML:
<p><input type="checkbox" name="extras[]" value="option1" rel="11">furniture</p>
<p><input type="checkbox" name="extras[]"" value="option2" rel="12">tabs</p>
<p><input type="checkbox" name="extras[]" value="option3" rel="13">urine</p>
<p><input type="checkbox" name="extras[]" value="option4" rel="30">couch</p>
<p><input type="checkbox" name="extras[]" value="option5" rel="20">steam</p>
<span id="output"></span>
This is my javascript function
$(document).ready(function() {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
This is my email reply/datbase inserting at the moment
$idextra=$_POST['extras'];
$arr_num=count($idextra);
$i=0;
while ($i < $arr_num)
{
$q="INSERT INTO bs_reservations (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine) VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff."','{$idextra[1]}','{$idextra[2]}','{$idextra[3]}','{$idextra[4]}','{$idextra[5]}','{$idextra[6]}')";
$res=mysql_query($qu) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
Thanks heaps for any advice/help in coding this. I know its a big question but I feel it will help a lot of people in the future.
$res=mysql_query($qu)
change that to
$res=mysql_query($q)
and probably this too
name="extras[]"" to name="extras[]"
and i think array starts with 0, and the query would be:
while ($i < $arr_num){
$q = "INSERT INTO bs_reservations";
$q .= " (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine)";
$q .= " VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff;
$q .= "','".$idextra[0]."','".$idextra[1]."','".$idextra[2]."','".$idextra[3]."','".$idextra[4]."','".$idextra[5]."')";
$res=mysql_query($q) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
Related
I have input field checkboxes,
<input value="1" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
<input value="2" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
<input value="3" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
My problem is that in my foreach loop insert query if I checked all the checkbox,
It will just insert value 1 and 2 in my database it ignores the value 3.
I'm using jquery and ajax to get the checkboxes.
var rubricChkbox = new Array();
$(".rubricChkbox:checked").each(function() {
rubricChkbox.push($(this).val());
});
console.log(rubricChkbox);
$.ajax({
url: "Queries/save.php",
type: "POST",
data: {
"rubricChkbox":rubricChkbox
},
success: function(yey){
console.log(yey);
alert(yey);
}
});
});
});
And this is my save.php,
if (isset($_POST['rubricChkbox']) || isset($_POST['uncheked']) || isset($_POST['user_id'])) {
$rubric_value = $_POST['rubricChkbox'];
$IDuser = $_POST['user_id'];
foreach($rubric_value as $rubric_check) {
$sql_check = "SELECT raw_selected_rubric FROM rubric_selected INNER JOIN cmat_composition ON rubric_selected.ID_cmat = cmat_composition.ID_cmat WHERE rubric_selected.ID_users = '$IDuser' AND raw_selected_rubric = '$rubric_check'
AND rubric_selected.Saved = '1'";
$result_check = mysqli_query($conn,$sql_check);
if (mysqli_num_rows($result_check) <= 0){
$sql_raw = "INSERT INTO rubric_selected (raw_selected_rubric, Saved, ID_users)
VALUES ('$rubric_check', '1', '$IDuser')";
mysqli_query($conn, $sql_raw);
}
}
What did I missed out? Thank you.
The best advice for you is that if something doesn't work the way you want, you should examine what happens at each step until you find the problem. This doesn't only apply to this question, but to any programming problem (and many others).
In this case
Is the data sent from the browser correct? You already have the statement console.log(rubricChkbox);. Did you check that value? Why didn't you include it in the the question?
Does the correct data arrive at the PHP script? Use something like print_r ($_POST);.
The SQL INSERT depends on the result of a SQL SELECT. Did you check that this condition is true, because otherwise your code wont even try to insert.
Does the INSERT statement return some error?
I have a table with 7 columns populated from mysql... the table headers each contain a checkbox which if checked and clicked on submit will be sent to a export to csv page.
Is there a way to use the SELECT $var1, $var2...$var7 FROM... ? $var1 to $var7 will be used if checkbox checked and if no checkbox checked then display some message
To betted understand what i am asking i'll put some code...
HTML
<td class="captabel">
<input type="checkbox" value="expid" >
</td>
<td class="captabel">
<input type="checkbox" value="exploc" >
</td>
etc
php
if(isset($_POST['expid'])){
$expid="id";
}
else{
$expid="";
}
if(isset($_POST['exploc'])){
$exploc="locatie";
}
else{
$exploc="";
}
etc
and at some point comes the SELECT * FROM table... <-- this is what i want to replace with SELECT $expid, $exploc ... FROM table...
i have tried various ways and none worked.
Thanks.
You have to use the name attribute on your checkbox
<input type="checkbox" value="123" name="expid" />
Modify your input type <input type="checkbox" name="exploc" value="exploc">
In your php script check :
$selectStr= "";
if(!empty($_POST['expid'])) {
$selectStr="id";
}
else{
$selectStr="";
}
if(!empty($_POST['exploc'])) {
$selectStr= !empty($selectStr) ? ", locatie" : "locatie";
}
else{
$selectStr="";
}
so your query will be
if(!empty($selectStr)) {
$qry = "SELECT $selectStr FROM table...";
}
Instead of setting different name you can set array type name in <input type="checkbox" value="exploc" name="exploc[]">
Solved it.
Based on Dipanwita Kundu answer i used
if(!empty($columns)){
$sql = 'SELECT '. implode(', ', $columns). ' FROM raport' ;
}
and works like a charm.
Thank you.
I have created a form that requires the user to input information on all fields and then submit the form. My goal is to get the user input and insert it into new records on the database. My current challenges are that since I used a for loop in PHP to create the table/form:
I can not access the input from $_POST
Not sure how to go about differentiating all of the rows and their inputs from each other (since I used a loop to create them). I was thinking an array...
Please see a screenshot of the form I am working with.
Below is what I have for my submit button.
if (isset($_POST['submit'])) {
$date = date('m\/d\/Y');
$ordnum = $_POST['cpOrderNumber'];
$ponum = $_POST['cpPoNumber'] . $_POST['cpPoNumberF'];
$palnum = $_POST['palnum'];
$casecount = $_POST['casecount'];
$cpsflot = $_POST['cpsflot'];
$sscc = $_POST['sscc'];
if(!empty($_POST['cpOrderNumber']) || !empty($_POST['cpPoNumber'])) {
require_once('mydatabase.php');
$query = "INSERT INTO ASN (date, ordnum, ponum, palnum, casecount, cpsflot, sscc )
VALUES ('$date', '$ordnum', '$ponum', '$palnum', '$casecount', '$cpsflot', '$sscc')";
$insert = sqlsrv_query($dbc, $query);
if( $insert === false ) {
die('Could not connect to database');
}
}
else {
die('Please enter the appropriate information');
}
sqlsrv_close($dbc);
}
And here is where I am having difficulty. I can get $date, $ordnum, and $ponum to insert into the database however $palnum will not. As you can see from what I've commented out I have tried to use an array.
<?php
for ($x = 1; $x < 25; $x++) {
echo
'<tr id="' .$x. '">
<td style="font-size: 160%" name="palnum" id="pallet">' .$x. '</td>
<td id="caseCount"><input type="number" name="casecount" id="inputText_Small" maxlength="2"/></td>
<td id="hilltopLot"><input type="text" name="cpsflot" id="inputText_Order" value="" maxlength="10"/></td>
<td id="sscc"><input type="number" name="sscc" id="inputText_Medd" value="" maxlength="4"/></td>
</tr>';
$palnum[$x] = $x;
//$palnum[$x] = 'palnum'.$x;
//$palnum = $palnumx.$x;
//$palnum1 = $palnum[1];
}
//echo count($palnumx);
//echo $palnum[1];
?>
i think you are looking for this. not 100% though. Basically, you can name an input wityh brackets to make it behave like an array in the post.
<input name="recurringName[]" value="moo" />
<input name="recurringName[]" value="moo2" />
if you do that, in the post you can access data this way
$_POST['recurringName'][0] == 'moo'
$_POST['recurringName'][1] == 'moo2'
i hope this helps! let me know if i did not understand you clearly
I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}
I have a form with several checkboxes which values are pulled from a database.
I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.
Here's the code:
<form id="form1" name="form1" method="post" action="">
<?php
$info_id = $_GET['info_id'];
$kv_dodatoci = mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: ' . mysql_error());
while ($kol = mysql_fetch_array($kv_dodatoci)){
$id_dodatoci = $kol['id_dodatoci'];
$mk = $kol['mk'];
echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="' . $id_dodatoci . '" />';
echo '<label for="' . $id_dodatoci.'">' . $mk . '</label><br />';
}
?>
<input type="hidden" value="<?=$info_id?>" name="info_id" />
<input name="insert_info" type="submit" value="Insert Additional info" />
</form>
<?php
if (isset($_POST['insert_info']) && is_array($id_dodatoci)) {
echo $id_dodatoci . '<br />';
echo $mk . '<br />';
// --- Guess here's the problem ----- //
foreach ($_POST['id_dodatoci'] as $dodatok) {
$dodatok_kv = mysql_query("INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')") or die('ERROR INSERTING: '.mysql_error());
}
}
My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database.
Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.
You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.
What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.
Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):
HTML:
<input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form.
PHP:
if (isset($_POST["ShowCloseWindowLink"])) {
$ShowCloseWindowLink=1;
} else {
$ShowCloseWindowLink=0;
}
.....
$sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..."
(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)
As an extra note: You're using the wrong HTML syntax for IDs and <label>. <label>'s "for" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.
Also, you're not validating your code at all. At the very least, do a htmlspecialchars() or htmlentities() on the input before you output it and a mysql_real_escape_string() before you insert data into the DB.
2nd Answer:
You might do something like this:
HTML:
echo '<input type="checkbox" name="id_dodatoci[]" value="'.$id_dodatoci.'" />';
PHP:
if ( !empty($_POST["id_dodatoci"]) ) {
$id_dodatoci = $_POST["id_dodatoci"];
print_r($id_dodatoci);
// This should provide an array of all the checkboxes that were checked.
// Any not checked will not be present.
} else {
// None of the id_dodatoci checkboxes were checked.
}
This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.
This might help too:
http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php
This is the loop that I needed. I realized that I need a loop through each key with the $i variable.
if(isset($_POST['id_dodatoci'])){
$id_dodatoci=$_POST['id_dodatoci'];
$arr_num=count($id_dodatoci);
$i=0;
while ($i < $arr_num)
{
$query="INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id)
VALUES ('$id_dodatoci[$i]','$info_id')";
$res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
}
Well, as Eli wrote, the POST is not set, when a checkbox is not checked.
I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.
Example:
<input type="checkbox" name="my_checkbox[<?=$id_of_checkbox?>]">
<input type="hidden" name="array_checkboxes[<?=$id_of_checkbox?>]" value="is_on_page">
So I get in the $_POST:
array(2){
array(1){"my_checkbox" => array(1){[123]=>"1"}}
array(1){"array_checkboxes" => array(1){[123]=>"is_on_page"}}
}
I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:
foreach ($_POST["array_checkboxes"] as $key => $value)
{
if($value=="is_on_page")
{
$value_of_checkbox[$key] = $_POST["my_checkbox"][$key];
//Save this value
}
}
Also something that few people use but that is quite nice in HTML, is that you can have:
<input type="hidden" name="my_checkbox" value="N" />
<input type="checkbox" name="my_checkbox" value="Y" />
and voila! - default values for checkboxes...!