Select List with a NULL that gets committed in SQL - php

I have a select list like the following inside of a form.
<select name="0[voicemail]" >
<option value="" selected="selected"></option>
<option value="800">800</option>
<option value="801">801</option>
<option value="802">802</option>
<option value="803">803</option>
<option value="805">805</option>
<option value="807">807</option>
<option value="808">808</option>
<option value="809">809</option>
<option value="810">810</option>
<option value="811">811</option>
<option value="820">820</option>
<option value="830">830</option>
<option value="831">831</option>
<option value="9778">9778</option>
<option value="9995">9995</option>
</select>
This was generated by some Kohana PHP code.
$id = 0;
$disabled = '';
foreach ( $line_detail as $line ){
echo '<tr class="d'.($id & 1).'">';
echo '<td>'.$line->did.form::hidden($id."[did]", $line->did).'</td>';
echo '<td>'.form::input($id."[cid_prefix]", $line->cid_prefix).'</td>';
echo '<td>'.$line->type.'</td>';
echo '<td>'.form::input($id."[ivr_context]", $line->ivr_context, "disabled='true'").'</td>';
if ($line->ivr_context != ''){
$disabled = "disabled='true'";
echo '<td>'.form::input(array('name'=>$id."[dial_timeout]", 'size'=>15,
'maxlength'=>3), $line->dial_timeout, $disabled).
form::hidden($id."[dial_timeout]", $line->dial_timeout).'</td>';
echo '<td>'.form::dropdown($id."[voicemail]", $phones, $line->voicemail, $disabled).
form::hidden($id."[voicemail]", $line->voicemail).'</td>';
} else {
echo '<td>'.form::input(array('name'=>$id."[dial_timeout]", 'size'=>15,
'maxlength'=>3), $line->dial_timeout, $disabled).'</td>';
echo '<td>'.form::dropdown($id."[voicemail]", $phones, $line->voicemail, $disabled).'</td>';
}
echo '<td>'.form::input($id."[notes]", $line->notes).'</td>';
echo "</tr>";
$id++;
}
Not everything shown, but basically the options are in the $phones variable.
Now the problem.
When I use a form submit all is fine until I choose the empty value in the submit.
This is inside a method where $detail is equivalent to $_POST
foreach($detail as $key => $val){
$this->db->query("UPDATE dids SET cid_prefix=?, dial_timeout=?, voicemail=?, notes=? WHERE did=?",
array($val['cid_prefix'],
$val['dial_timeout'],
$val['voicemail'],
$val['notes'],
$val['did']));
The problem here is that I set the value for the empty option to be "NULL", but because Kohana adds commas around everything it inserts it'll try to put "NULL" into the database instead of NULL. In this case this will violate a foreign key constraint.
Is there a simple way to deal with NULL in PHP/Kohana so that I don't have to check for blank and rewrite each query that might contain NULL more than one time.
What happens when you could get multiple valid NULLs? Surely there is a way to deal with these types of situations simply?

Placing this code before the database update seems to fix the problem. I.e. set $val['voicemail] to the PHP constant NULL.
if (empty($val['voicemail'])){
$val['voicemail'] = NULL;
}
Then I can continue to use the original SQL statement. Kohana seems to behave itself and NULL is set through in the update statement.

You can use the DB::expr method which will not escape the value in the query. That way you insert a raw NULL
However, I'm amazed you've used a object orientated framework and yet chucked out all the advantages by creating a mess of a form. Job security?

Related

How do I get the selected option value as a string in PHP?

My aim is to get the selected item from the drop down and covert it to type string. After conversion, am comparing the result with another string and then use if() statement to execute some code. But the conversion does not seem to work because the program only execute else() statement. How can I do this? somebody help Please.
Below is my html and php code.
<select name="p_category">
<option selected disabled >-- select --</option>
<option value="computers">Computer</option>
<option value="phones" >Phone</option>
<option value="accessories">Accessory</option>
<option value="general">Display</option>
</select>
<?php
$getCategory = $_POST['p_category'];
$value = strval($getCategory);
$comps = "computer";
if($value == $comps){
echo "<script>alert('Equal')</script>";
}else{
echo "<script>alert('Not equal')</script>";
}
?>

How to set an option from multiple options or array with different values to views as selected in select box using PHP

An option value is taken from the database and included in a select box along with other options. How can I set the value taken from the database as selected?
The value from the database is set as $row['value'] and equals s. In HTML the options look like so...
<select name="select">
<option value='xxs'>Extra, Extra small</option>
<option value='xs'>Extra small</option>
<option value='s'>Small</option>
<option value='m'>Medium</option>
<option value='l'>Large</option>
<option value='xl'>Extra Large</option>
<option value='xxl'>Extra, Extra small</option>
</select>
What I want is the $row['value'] (Small) option to be displayed on page load... Is this possible?
The good news is, this is possible and in PHP is quite simple really. First we put all of our options and their respective values in an array like so:
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
Follow this by opening the select box and calling upon the options array in a foreach loop...
echo '<select>';
foreach($options as $view=>$value){
As you may have noticed the array contains fields that look like 'Large'=>'l' and the for each loop is calling upon the options as $view=>$value. $view represents the name field, in this case 'Large' and $value represents the value field 'l'. This is important if you expect the user to see different options in the select box than what the values are set at.
Next we create the variable $selected which is going to be used to determine if there is a match between $row['value'] and $value...
$selected=($row['value'] == $value)? "selected" : "";
This is the same as using an if and else statement to set the variable, but shorter. The first section after the variable is asking if $row['value'] is equal to $value, if it does then $selected="selected" else (:) $selected is set to blank.
Next we include the options. Because it is in the foreach loop, we only need one line to insert all of the options...
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
Remember the $selected variable in the last step? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row['value'] equals $value. If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. It continues through the rest of the array until all views and values have been scanned and returns their respective options.
Finally we close the foreach loop and the select box...
}
echo '</select>';
And there you have it, an automatic way to make a select box option set as selected. A similar pattern can be used for check-boxes, radio selectors, tabs and more.
The full code...
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
echo '<select>';
foreach($options as $view=>$value){
$selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}
echo '</select>';
Given this array, and this value to be the selected value...
$options = array(
'Extra, Extra small' => 'xxs',
'Extra small' => 'xs',
'Small' => 's',
'Medium' => 'm',
'Large' => 'l',
'Extra Large' => 'xl',
'Extra, Extra Large' => 'xxl'
);
$selected = 'm'; // $selected can be swapped for $row['value'] as in the OP
There are several ways to dynamically construct the option tags inside of a <select> and set the selected attribute on one of them.
First the one-liner inside a foreach loop:
echo "<select name=\"select\">";
foreach($options as $text=>$value){
echo "<option value=\"$value\"" , ($selected == $value ? " selected" : "") , ">$text</option>";
}
echo "</select>";
This code block uses a ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon. Go here for further reading and examples.
By using double quotes " you avoid having to toggle back and forth between literal strings and variables. *You will have to escape double quotes that are nested inside of the string by prepending \. *Variables can be wrapped in curly brackets to isolate their variable name from the surround text. *Single quotes will not echo the value of the variable.) For continued read about quoting: reference
By using , (commas) instead of . (dots) to concatenate the string, performance is increased. one benchmark
By only adding a space before the selected attribute in the true condition (versus adding the space outside the condition on every iteration), you avoid creating unnecessary spaces inside your tag.
By using an inline condition statement, you avoid unnecessarily declaring a variable into the global scope. If you declare the selected string as a variable, as #independent.guru does, it will be declared/overwritten and used only once on every iteration; this can only decrease performance.
Each programmer will have their own preferences about "readability", "brevity", "consistency", and "performance" and may elect to construct their html using any mixture of the above techniques.
As a general rule, I don't bother to declare a variable that I will only use once. In my personal preference hierarchy, brevity, consistency, and performance always come before readability.
Some of the above points may seem like micro-optimizations, but for a canonical question, it is reasonable to include discussion on performance as any of the listed methods may be copy-pasted directly into projects.
If the first code block was too compact, here are two other versions that spread out the method over multiple lines without generating any extra variables:
Separated shorthand if/else syntax:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
echo $selected == $value ? " selected" : "";
echo ">$text</option>";
}
echo "</select>";
Standard if conditional:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
if($selected == $value){
echo " selected";
}
echo ">$text</option>";
}
echo "</select>";
All of the above versions of the same method will create this rendered html:
When the page is loaded:
When the select element is opened:
The source code will look like this:
<select name="select"><option value="xxs">Extra, Extra small</option><option value="xs">Extra small</option><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option><option value="xl">Extra Large</option><option value="xxl">Extra, Extra Large</option></select>
This is the source code tabbed out for easier reading:
<select name="select">
<option value="xxs">Extra, Extra small</option>
<option value="xs">Extra small</option>
<option value="s">Small</option>
<option value="m" selected>Medium</option>
<option value="l">Large</option>
<option value="xl">Extra Large</option>
<option value="xxl">Extra, Extra Large</option>
</select>

Error while getting select box value with php

I am currently working on a project where a user chooses an option from a select box and submits a form, the form is then processed by PHP, and the PHP code determines what the select box value is, and does something based on that value.
My select box is called combined_group and has two select values: philharmonic_orchestra and symphony_orchestra.
This is how I am checking the selected value:
if($_POST['combined_group'] == "philharmonic_orchestra"){
$_SESSION['semesterprice'] = "170";
$_SESSION['fullprice'] = "330";
}
if($_POST['combined_group'] == "symphony_orchestra"){
$_SESSION['semesterprice'] = "275";
$_SESSION['fullprice'] = "530";
}
But when PHP runs through this code, neither if statement is chosen. I know that the value of $_POST['combined_group'] is, in fact, either of those two values, just PHP isn't picking it up for some reason.
Anybody care to help?
EDIT: My HTML form code is as follows
<select name="combined_group" class="OBJ-1">
<option value="" selected="">Select One</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra ">Symphony Orchestra</option>
</select>
Client side
<select name="combined_group">
<option value="">Select an option</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra">Symphony Orchestra</option>
</select>
Server side
if (! isset($_POST["combined_group"]))
{
exit('not set');
}
if (trim($_POST["combined_group"]) == '')
{
exit('not selected');
}
if (trim($_POST["combined_group"]) == 'philharmonic_orchestra')
{
//business logic for 'philharmonic_orchestra'
}
else
{
//business logic for 'symphony_orchestra'
}
Most likely is a bad HTML syntax. Check if your option item has value attribute:
<option value="...">...</option>
The reason why your conditional statement is failing, is because of a space in your option's value.
<option value="symphony_orchestra ">
^ right there
What you will need to do is remove it:
<option value="symphony_orchestra">
^ deleted space
Technical sidenote:
Had your conditional statement been:
if($_POST['combined_group'] == "symphony_orchestra ")
^ notice the space
with the space before the quote, it would have worked.
Anything between quotes is considered and part of an element's value.

why won't my drop-box be populated correctly using a while statement?

i have a problem with a drop-box that isn't populated correctly.
echo"<td>Selectati numarul de telefon:</td>
<td><select name='mobil'>
<option value='--'>---</option>";
while($apelantRow = mysql_fetch_assoc($apelantResult))
{
$apel=(string)$apelantRow['nrtel'];
echo "<option value='".$apel."'>$apel</option>";
}
echo"</select></td></tr>";
the sql query works fine. what i get is something like this:
<option value='2'>1</option>
<option value='2'>2</option>
I really don't know what to do. what is confusing me is that i have the same code, on an other page, with different variables and it works just fine.
please help.
thanks,
Sebastian
Why not
echo '<option value="'.$apel.'">'.$apel.'</option>';
?
EDIT : explicit cast doesn't required as variable is used in a string

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

Categories