Insert boolean + results to mysqlDB - php

Writing a section of a long form to add data to MySQL database and in this form
a boolean checkbox that allows a section to show or hide and I need to insert this boolean to database with the other data
Later I need to get this data from database and show it in front end....
So it will say
Yes (section is true and showing) + the rest of data in the section
My problem is in boolean checkbox to insert it as "YES allowed" to retrieve it later and say "Yes it's Allowed + data" .. I know it's easy but I'm at point of complete confusion
<label>Pets Allowed:</label>
<input class="form-pine" type="checkbox" name="pets" id="petscheck" value="<?php if(isset($result->dogs_permit)){ echo $result->dogs_permit; } ?>" onchange="valueChanged()"><br>
<script type="text/javascript">
function valueChanged() {
if (document.getElementById('petscheck').checked) {
document.getElementById("petsshowhide").style.display = 'block';
} else {
document.getElementById("petsshowhide").style.display = 'none';
}
}
</script>
<div class="col-pine-2" id="petsshowhide" style="display:none;">
<label>Pets fees:</label>
<select class="form-pine" name="dogs-fees">
<option value="">Select Option</option>
<option value="Inclusive"<?php if(isset($result->dogs_fees) && $result->dogs_fees == '0'){ echo 'selected'; } ?>>Inclusive</option>
<option value="Additional Charge"<?php if(isset($result->dogs_fees) && $result->dogs_fees == '1'){ echo 'selected'; } ?>>Additional Charge</option>
</select>
<label>pets Fees:</label>
<input class="form-pine" type="number" name="pets-price" value="<?php if(isset($result->dogs_price)){ echo $result->dogs_price; } ?>">
<label>currency:</label>
<select class="form-pine" name="dogs-curr">
<option value="">Select currency</option>
<option value="USD"<?php if(isset($result->dogs_curr) && $result->dogs_curr == 'USD'){ echo 'selected'; } ?>>USD</option>
<option value="EUR"<?php if(isset($result->dogs_curr) && $result->dogs_curr == 'EUR'){ echo 'selected'; } ?>>EUR</option>
</select>
</div>
function add
if(isset($_POST['submitpineapple'])){
global $wpdb;
$table_pine = $wpdb->prefix . 'ppf_admin';
$dogs_permit = $_POST['pets'];
$dogs_fees = $_POST['dogs-fees'];
$dogs_price = $_POST['pets-price'];
$dogs_curr = $_POST['dogs-curr'];
if(isset($_POST['adds_pineapple'])){
$pid = $_POST['adds_pineapple'];
$sql = "INSERT INTO $table_pine (dogs_permit, dogs_fees, dogs_price, dogs_curr) VALUES ($dogs_permit, '$dogs_fees', $dogs_price, '$dogs_curr')";
if($wpdb->query($sql)){
echo'<div class="success-msg">Save Successfully</div>';
}else{
echo'<div class="errorcss">Something went wrong!</div>';
}

You can store pets as 1 if it is selected or 0 if it is not selected in the table. Or in a parent table.
You will have $_POST['pets'] available when it is selected. You can check for this with isset($_POST['pets']) and get 1 or 0 with $dogs_permit=isset($_POST['pets'])? 1 : 0;

Related

PHP - Edit page , How to set default dropdownlist that have option from MySQL?

I know only this method. this method is assume that you know the values in all <option>
<select name="agama" id="agama">
<option value="Islam"<?php if ($rows['agama'] === 'Islam') echo ' selected="selected"'>Islam</option>
<option value="Khatolik"<?php if ($rows['agama'] === 'Khatolik') echo ' selected="selected"'>Khatolik</option>
<option value="Protestan"<?php if ($rows['agama'] === 'Protestan') echo ' selected="selected"'>Protestan</option>
<option value="Hindu"<?php if ($rows['agama'] === 'Hindu') echo ' selected="selected"'>Hindu</option>
<option value="Buddha"<?php if ($rows['agama'] === 'Buddha') echo ' selected="selected"'>Buddha</option>
<option value="Lain-Lain"<?php if ($rows['agama'] === 'Lain-Lain') echo ' selected="selected"'>Lain-Lain</option>
</select>
.... the above code is example from other people not mine.
but My case is the <option> is select from database too.
I have 2 table, oav_event and oav_album
the oav_album has foreign key (event_id) from oav_event table
I want to check if row['event_id'] from oav_album table is equal to option value (from oav_event table) if true, then set selected="selected"
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row['event_id']; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
the option will change depend on change in database table, so I don't know the value in option. How should I do?
<select name="event_id">
<?php
$sql = "SELECT * FROM oav_event";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$selected = "";
if($row['event_id'] == $Yourmatchvalue)
{
$selected = "selected";
}
?>
<option value="<?php echo $row['event_id']; ?>" selected="<?php echo $selected; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
</select>
may this helps your. you need to replace $Yourmatchvalue variable with your variable.
You can use $_GET as the method on your form and pass the id of the record using it:
while($row = mysqli_fetch_assoc($result)) {
if (!empty($_GET['event_id']) && $row['event_id'] == $_GET['event_id']) {
$selected = 'selected = "selected"';
} else {
$selected = '';
}
echo '<option '.$selected.' value="'.$row["event_id"].'">'.$row["event_date"].'</option>';
}
Here is a solution,
$selected_value = 'Hindu'; // This will come from database
Change option tag with this
<option value="<?php echo $row['event_id']; ?>" <?php echo ($row['event_id'] == $selected_value) ? 'selected="selected"' : ''; ?> >Event: <?php echo $row['event_date']; ?> </option>
Create one function which will create options list like this:
function setDropdownValue($selectQueue_list,$selectedVal)
{
$queueVal = '';
$selectQueue_list_res=$db->query($selectQueue_list);
while($selectQueue_list_res_row=$db->fetchByAssoc($selectQueue_list_res))
{
$val = $selectQueue_list_res_row['id'];
$name = $selectQueue_list_res_row['name'];
if($val == $selectedVal)
{
$queueVal .= "<option value='$val' selected='selected' label='$name'>$name</option>";
}
else
{
$queueVal .= "<option value='$val' label='$name'>$name</option>";
}
}
return $queueVal;
}
Then create a query:
$get_value_query="SELECT id, name FROM table";
$dropdown_selected_value = !empty($dropdown_value) ? $dropdown_value: ''; // Pass value which you want to be selected in dropdown
Then call this function:
$dropdown_options = setDropdownValue($get_value_query, $dropdown_selected_value);
Later when you get dropdown options in $dropdown_options, use jquery to populate the dropdown, like this:
$('#dropdown_select_id').html("$dropdown_options");
Give it a try, and let me know.

Alternative for huge database list

Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.

Retaining dropdown values after submitting form using GET method

I am using dropdown to select values, and after I click the submit button, my values change. Please help me retain the selected values. Using POST method I have got the solution, but I want to use with GET method. Is it possible?
1.) 1st select stmt:
<form action="" method="GET">
<select name="sort" >
<option value="inc_patientName">Patient Name</option>
<option value="inc_date">Date</option>
<option value="inc_status">Status</option>
<option value="inc_patientAge">Age</option>
</select>
<input type="submit" name="GETREPORT" value="Get Report"/>
if ($_GET)
{echo"hi";}
</form>
2.) 2nd select with while
<?php
//Selecting ward from table ward master
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
echo "<select name='ward'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['ward_id'] . "'>" . $row['ward_name'] . "</option>";
}
echo "</select>";
?>
3.) 3rd select with javascript:
<select name="daydropdown" id="daydropdown" ></select>
<select name="monthdropdown" id="monthdropdown"></select>
<select name="yeardropdown" id="yeardropdown"></select>
<script type="text/javascript">
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
Javascript code:
<script type="text/javascript">
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield)
{
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=1; i<=31; i++)
dayfield.options[i]=new Option(i, i)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1999
for (var y=0; y<45; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
try
if(isset($_GET['sort'])) {
echo $_GET['sort'];
}
and get selected index
<option value="inc_patientName" <?php if (isset($_GET['sort']) && $_GET['sort'] == "inc_patientName") echo 'selected="seleceted"'; ?>>Patient Name</option>
and so on for all options values match
For 2nd dropdown:-
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['ward_id'];?>" <?php if (isset($_GET['sort']) && $_GET['sort'] == $row['ward_id']) echo 'selected="seleceted"'; ?>><?php echo $row['ward_name'];?></option>
<?php }
use it like this... it myt work.
<select name="ward">
<?php
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
if ($_GET['ward']==$row["ward_id"]) {
echo '<option selected="selected" value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
} else {
echo '<option value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
}
}
?>
</select>
You can do something like this:
<select name="sort" >
<option value="inc_patientName"<?php if ($_GET['sort'] == 'inc_patientName') echo ' selected="seleceted"'; ?>>Patient Name</option>
<option value="inc_date"<?php if ($_GET['sort'] == 'inc_date') echo ' selected="seleceted"'; ?>>Date</option>
<option value="inc_status" <?php if ($_GET['sort'] == 'inc_status') echo ' selected="seleceted"'; ?>>Status</option>
<option value="inc_patientAge"<?php if ($_GET['sort'] == 'inc_patientAge') echo ' selected="seleceted"'; ?>>Age</option>
</select>
Try this:
Use this function in ur script:
function setday(id,elementname)
{
document.getElementById(elementname).value=id;
}
Use this in ur php form, Repeat the same code for year and month dropdowns:
if (isset($_GET['daydropdown']))
{
echo "<script type='text/javascript'>setday('".$_GET['daydropdown']."','daydropdown')</script>";
}

JavaScript Display/Hide Fields not working - OnChange doesn't occur everytime

I am trying to hide and show fields based of the selection in a dropdown field. I got it do hide but when I select another value it doesn't display again.
<script type="text/javacript">
function checkEm(){
if (document.getElementById('JobTypeDDL').selected = "2"){
document.getElementById('DateTbx').style.visibility = "hidden";
document.getElementById('DateTbx').style.display = "none";
} else {
document.getElementById('DateTbx').style.visibility = "visible";
document.getElementById('DateTbx').style.display = "block";
}
}
</script>
<div class="InputField">
<select name="JobTypeDDL" id="JobTypeDDL" onChange="checkEm()">
<option value="0" <?php if ($_POST['JobTypeDDL'] == "0") {echo "selected='selected'";} ?> >Select Job Type</option>
<option value="1" <?php if ($_POST['JobTypeDDL'] == "1") {echo "selected='selected'";} ?> >New Mobility</option>
<option value="2" <?php if ($_POST['JobTypeDDL'] == "2") {echo "selected='selected'";} ?> >Service/Repair/Install</option>
</select>
</div>
<input name="DateTbx" id="DateTbx" type="text" <?php if (!$_POST['DateTbx'] == "") {echo "value='". $_POST['DateTbx']."'";} ?> />
Use == to test equality in an if statement. You are using =, which is assignment.
In the if condition you're using a single =. Use === instead.

PHP and HTML select tag

I have started with PHP and HTML and would like to execute simple code with three drop-down lists (select tag). But when I make selection from one, the other two selected values disappear. Should I save values when submitting them and then echo. If yes, how can I do it. Sample code will be appreciated.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))$name_vid=($_POST['vid']);
else $name_vid="no";
if (isset($_POST['type']))$name_type=sanitizeString($_POST['type']);
else $name_type="no";
if (isset($_POST['model']))$name_model=sanitizeString($_POST['model']);
else $name_model="no";
echo <<<_END
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option value = "apple">apple</option>
<option value = "cherry">cherry</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="type" size="1">
<option value="" selected>Color</option>
<option value = "green">green</option>
<option value = "red">red</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="model" size="1">
<option value="" selected>Model</option>
<option value = "1-a">1-a</option>
<option value = "2-b">2-b</option>
<option value = "3-c">3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
_END;
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I think you need to re-select the values of the drop downs after submission. The following code would be a fix.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "(nothing)";
if (isset($_POST['vid']) && $_POST['vid']) $name_vid=($_POST['vid']);
if (isset($_POST['type']) && $_POST['type']) $name_type=sanitizeString($_POST['type']);
if (isset($_POST['model']) && $_POST['model']) $name_model=sanitizeString($_POST['model']);
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="">Product</option>
<option value = "apple" <?php if($name_vid == 'apple') echo 'selected="selected"'; ?>>apple</option>
<option value = "cherry" <?php if($name_vid == 'cherry') echo 'selected="selected"'; ?>>cherry</option>
<option value = "orange" <?php if($name_vid == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="type" size="1">
<option value="">Color</option>
<option value = "green" <?php if($name_type == 'green') echo 'selected="selected"'; ?>>green</option>
<option value = "red" <?php if($name_type == 'red') echo 'selected="selected"'; ?>>red</option>
<option value = "orange" <?php if($name_type == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="model" size="1">
<option value="">Model</option>
<option value = "1-a" <?php if($name_model == '1-a') echo 'selected="selected"'; ?>>1-a</option>
<option value = "2-b" <?php if($name_model == '2-b') echo 'selected="selected"'; ?>>2-b</option>
<option value = "3-c" <?php if($name_model == '3-c') echo 'selected="selected"'; ?>>3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
<?php
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I would not use heredoc syntax ("<<<") to print HTML.
Try this out, i made one submit button, and re selected the values after submit :
<?php
// formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))
$name_vid = ($_POST['vid']);
else
$name_vid = "no";
if (isset($_POST['type']))
$name_type = sanitizeString($_POST['type']);
else
$name_type = "no";
if (isset($_POST['model']))
$name_model = sanitizeString($_POST['model']);
else
$name_model = "no";
///////////////////
if($name_vid == 'apple')
{
$v1 = 'selected';
}
elseif($name_vid == 'cherry')
{
$v2 = 'selected';
}
elseif($name_vid == 'orange')
{
$v3='selected';
}
////////////////////////
if($name_type == 'green')
{
$t1 = 'selected';
}
elseif($name_type == 'red')
{
$t2 = 'selected';
}
elseif($name_type == 'orange')
{
$t3='selected';
}
///////////////////////
if($name_model == '1-a')
{
$m1 = 'selected';
}
elseif($name_model == '2-b')
{
$m2 = 'selected';
}
elseif($name_model == '3-c')
{
$m3='selected';
}
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form name="fruite_form" action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option <?=$v1?> value = "apple">apple</option>
<option <?=$v2?> value = "cherry">cherry</option>
<option <?=$v3?> value = "orange">orange</option>
</select>
<select name="type" size="1">
<option value="" selected>Color</option>
<option <?=$t1?> value = "green">green</option>
<option <?=$t2?>value = "red">red</option>
<option <?=$t3?>value = "orange">orange</option>
</select>
<select name="model" size="1">
<option value="" selected>Model</option>
<option <?=$m1?> value = "1-a">1-a</option>
<option <?=$m2?>value = "2-b">2-b</option>
<option <?=$m3?>value = "3-c">3-c</option>
</select>
<input name="submitButtom" id="submitButton" type="submit"/><br />
</form>
</body>
</html>
<?
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
Feel free top add back your submit buttons.
But give each a unique name and also don't forget to name your form, and as a good practice, give then an id too which will be the same as name attribute.
Update: Just to make sure you are really getting a post, since this is your initial question, print this at the end of your code
echo $_POST['vid'] . ' ' . $_POST['type'] . ' ' . $_POST['model'] . '<br/><br/>';
and see if post really holds the value after submission, if you get a value from post, but not from your assigned variables, then check your conditions used at the top to assign your values.
// you need to check if post isset and has an actual value, only than, the varibale should be assigned. Just like what Sithu said.

Categories