Dropdown function is losing words after space in submitted output - php

I'm trying to create my first function in PHP, a drop down. It's almost working, but when I submit/post the data the options with a space in it will only show the first word in the output.
In the example I have 'First Name' as an option in the drop down list. When I hit submit, the output will only be 'First'. When I change 'First Name' to 'First-Name' it works, the output is 'First-Name'. So I think I need to add quotes somewhere in the code so that it is handled as a string??
Hope someone can help me out, I'm so close to what I want.
<!DOCTYPE HTML>
<html>
<body>
<?php
include('db_functions.php');
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = clean_input($_POST['first_name']);
}
//drop down function
function dropdown($name, $options) {
$dropdown = '<select type="text" name='.$name.'>'."\n";
$rows = $options;
if($rows === false) {
$error = db_error();
}
$totalrows = count($rows);
for ($x = 0; $x < $totalrows; $x++) {
$dropdown .= '<option value=' . $rows[$x][$name] . '>' . $rows[$x][$name] . '</option>'."\n";
}
$dropdown .='</select>'."\n";
return $dropdown;
}
echo '<form action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
//start dropdown
echo 'First Name:';
$name = 'first_name';
$options = db_select("SELECT DISTINCT first_name FROM nametable GROUP BY first_name ORDER BY first_name ASC LIMIT 20");
echo dropdown($name, $options);
//end dropdown
echo '<input type="submit" name="submit" value="Submit">';
echo '</form>';
echo $fName;
?>
</body>
</html>

Your code is writing
<option value=First Name>
The space ends the value, so Name is a separate attribute. You need to put the value in quotes, so it's
<option value="First Name">
The code should be:
$dropdown .= '<option value="' . $rows[$x][$name] . '">' . $rows[$x][$name] . '</option>'."\n";

Related

Set the selected value in select2 multiple using PHP

How will i set the selected item in select2 multiple ? i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
<?php
$mytitle = array(
"867310020292434, 867310021548131, 867310021561670");
$test = implode(',', $mytitle);
$query=mysqli_query($link,"select * from inventory where ITEM_CODE_MX='OPP01-3006GRY'");
while($row=mysqli_fetch_array($query))
{
$imei=$row["IMEI_MX"];
$title = explode(',', $imei);
}
?>
<script>
$(function () {
$('#tags').select2();
function select (event){
$("#tags").select2({
maximumSelectionLength: $('#quantitytotransfer').val(),
formatSelectionTooBig: function (limit) {
$('#box').show().text('Callback!');
parseInt($("#quantitytotransfer").val())
return 'Too many selected elements (' + limit + ')';
}
});
}
$('#quantitytotransfer').on('keyup', select);
select()
});
</script>
<select id="tags" name='title[]' style="width:300px;" class="form-control select2-offscreen" onchange="getCount()" multiple>
<?php
foreach ($title as $opt) {
$sel = '';
$wew = trim($is);
if (in_array($opt, $mytitle)) {
$sel = 'selected="selected" ';
}
if (!empty($opt)) {
echo "<option ' . $sel . ' value='$opt'>$opt</option>";
}
}
?>
</select>
if you want to select the first option here is the code
$sel = "selected";
foreach ($title as $opt) {
if (!empty($opt)) {
echo "<option value='" . $opt . "'" . $sel . ">" . $opt . "</option>";
$sel = "";
}

Get data from DB to set as default in dropdown HTML/CSS/MYSQL/PHP

Hello guys I want to get data from the DB to set as default/selected in my dropdown.
I have a page named Update Project, in that page I have a dropdown component that is filled by records from my data, however I want to set the selected value from the query result.
This is what I've tried so far:
$st_ac = $conn->prepare( "SELECT p.project_code, m.type
FROM tblprojects as p
JOIN tblprojectsmaster as m
ON p.project_code = m.project_code
WHERE p.project_code = :code" );
$st_ac->execute(array(':code' => $code));
$result = $st_ac->fetch(PDO::FETCH_ASSOC);
$ptype = $result['type']; // the data to be selected in the dropdwon
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value"' . $type . '"';
if($ptype == $type)
echo 'selected="selected"';
echo '>' . $description . '</option>';
echo '<br />';
?>
<option value="<?php echo $type; ?>"><?php echo $description; ?></option>
<?php
}
?>
But I can't be able to achieve what I want. Any ideas? Your help will be truly appreciated. Thanks.
Try this
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value="'.$type.'"';
if($ptype == $type)
{
echo 'selected="selected"';
}
echo '>'.$description.'</option>';
}
?>
May be you can use like this
echo '<option value="' . $type . '"'; if($ptype == $type) { echo 'selected="selected" } >'; echo $description . '</option>'; echo '<br />';

How to set multiple select options by default from array

I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";
I think you may have a logic error. Try this as your loop:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Use the in_array() function.
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example

selected option in select dissappears on reload

Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";

php how to divide a list of while loop result

PHP:
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
echo '<p><input type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
RESULT:
<input type="checkbox" value="Crows feet">Crows feet
<input type="checkbox" value="Frown lines" >Frown lines
<input type="checkbox" value="Lip augmentation">Lip augmentation
<input type="checkbox" value="Lip lines">Lip lines
<input type="checkbox" value="Marionette lines">Marionette lines
i want the result:
**LEFT** **RIGHT**
<input type="checkbox">Crows feet |<input type="checkbox" >Lip lines
<input type="checkbox">Frown lines | <input type="checkbox">Marionette lines
<input type="checkbox"">Lip augmentation
Could you not alternate a class on each second input that suggests clearing a float or something similar if you are not floating the inputs? Something along the lines of:
function get_t_wrinkle_rel(){
global $mysqli;
$flag = 1;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
if ($flag = 1) {
$orientate=left;$flag=0;
} else {
$orientate=right;$flag=1;
}
echo '<p><input class="' . $orientate . '"type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
while ($left = $q->fetch_array()) {
echo '<p>';
echo '<input...>' . $left['...'];
if ($right = $q->fetch_array()) {
echo '| <input...>' . $right['...'];
}
echo '</p>';
}
This way should fill the left column in order then the right column, keeping the order you want to achieve. I don't have access to your database so I can't test this, but it should do the job.
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
$mid = floor($q->num_rows/2); // Get halfway point
$count = 0;
$array = array();
while($r = $q->fetch_array()){
$string = '<input type="checkbox" value="'.$r['t_wrinkle_name'].'" />'.$r['t_wrinkle_name'];
if($count <= $mid){
// Left column
$array[$count] = $string;
} else {
// Right column
$array[$count-$mid] .= '|'.$string;
}
$count++;
}
// Make single string
echo implode('', $array);
}
However I would recommend using the idea biscuitstack suggested, using CSS to position it the way you want, rather than doing it programatically. It's always better to try to keep presentation separate from the logic wherever possible.
You could use flag that increments everytime and
<input type="checkbox"' . $r['t_wrinkle_name'] .
if flag % 2 == 0 then echo '<br />'
Or something like that.

Categories