dropdown box has extra blank spaces/vaues - php

I am grabbing some values from my database and putting them in a dropdown select box. For some reason, there is a blank value after each option, which is weird as my database doesn't contain any blank fields.
<select id="school" name="school_name">
<option value=0> Choose</option>
<?php
$con = mysqli_connect("localhost", "root", "****") or die("error".mysqli_error());
mysqli_select_db($con, "newprojectdb") or die("error in database".mysqli_error());
$sql="SELECT school_id, school_name FROM schools";
$result=mysqli_query($con, $sql);
while($row= mysqli_fetch_array($result)){
$school_name=$row["school_name"];
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
}
mysqli_close ($con);
?>
</select>

The reason why you are getting a blank space between each value is because of the last <OPTION> which the closing / was missing and should have been closed like this </OPTION>
I also noticed you escaped the single quotes for
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
^^ ^^ ^ missing the / slash
which would not have echo'ed the value in HTML source but the variable itself $school_name
Sidenote: Variables are not parsed properly when set inside single quotes which is what you were doing in escaping the single quotes.
Example:
<OPTION VALUE='$school_name'>
Change it to:
echo '<OPTION VALUE="'.$school_name.'">'.$school_name.'</OPTION>';
and it will work.
You can also do it this way: (escaping the double quotes for VALUE instead).
echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>";
Footnotes
For cleaner and more readable HTML, use a concatenated . "\n" at the end like this:
echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>" . "\n";
which will produce something like:
<OPTION VALUE="St-Alexander">St-Alexander</OPTION>
<OPTION VALUE="St-Peter">St-Peter</OPTION>
<OPTION VALUE="St-John">St-John</OPTION>
instead of
<OPTION VALUE="St-Alexander">St-Alexander</OPTION><OPTION VALUE="St-Peter">St-Peter</OPTION><OPTION VALUE="St-John">St-John</OPTION>

Pleae find changes you need. Thanks
CHANGE
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
TO
echo "<option value=\"$school_name\"> $school_name </option>";

Related

UPDATING information into MySQL Database but department remains the same for each employee

I am trying to update my DB for the employees table. When I run and test, every user is coming up as working in Accounting even if they work in another department. Is there something I am missing? I am not receiving any errors either. Any help is greatly appreciated.
PHP/HTML
<?php
//ERROR CHECKING CODE
mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once("dbconnect.php");
$id = (isset($_REQUEST['id']) ? $_REQUEST['id'] : '');
$sql = "SELECT * FROM employees WHERE empid= '" . $id . "';";
$result = mysqli_query($connect, $sql) or die(mysql_error);
$row = mysqli_fetch_array($result, MYSQL_ASSOC) or die (mysql_error());
?>
PHP/HTML
<p>Department</br>
<select name="department">
<option <?php if($row['department']==1) {print('selected');}?>value="1">Accounting</option>
<option <?php if($row['department']==2) {print('selected');} ?>value='2'>Legal</option>
<option <?php if($row['department']==3) {print('selected');} ?>value='3'>Information Technology</option>
<option <?php if($row['department']==4) {print('selected');} ?>value='4'>Human Resources</option>
</select>
Without seeing the code in action it's hard to say, but at first glance there's this problem: In each option tag you're not leaving any space between the closing PHP tag (?>) and the value property, so when if $row['department'] matches the correspondent value, the PHP statement will print "selected" but with no space, the HTML will look like this (say $row['department'] equals 2):
<option selectedvalue='2'>Legal</option>
which obviously won't select that option. Try adding a space after each closing PHP tag, or print "seleted ", with a space in the end.

populate html table with php from mySQL based on user input

I'm trying to populate an html table from my SQL query based on a user's selections. I'm able to populate the first column however, my variable column "select_datapoint" is blank. Is there any reason this won't work?
<form>
<select name="select_datapoint">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
<option value="test5">test5</option>
</select>
<select name="minput">
<option value="ME">ME</option>
<option value="CT">CT</option>
<option value="AZ">AZ</option>
<option value="DE">DE</option>
<option value="MT">MT</option>
</select>
<input type="submit" name="Submit">
</form>
<br></br>
<?php
print date("g:i a.", time());
?>
<br></br>
<!--use PHP to connect to sql database-->
<?php
$servername = "sql206.phpnet.us";
$username = "pn_14163829";
$password = "714405c";
$dbname = "pn_14163829_mexico";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$zurich = $_GET["minput"];
$montreal = $_GET["select_datapoint"];
$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table class=\"v\">";
echo "<th>test1</th><th>$montreal</th>";
while($row = $result->fetch_assoc()) {
echo "<tr>"."<td>".$row["test1"]."</td>"."<td>".$row['testX']."</td>"."</tr>";
}
} else {
echo "0 results";
echo "<br></br></table>";
}
$conn->close();
?>
$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
Mark's answer is correct, but not for the reason he gives.
He says that the above will treat '$montreal' as a string literal. Normally that is correct, but because it's embedded in a double quoted string, it will actually be interpolated correctly.
What's actually happening is that you're generating a string along the lines of:
SELECT test1,'fieldname' AS testX FROM test WHERE test1='$zurich'
The 'fieldname' is incorrect - it's a column name. Single quotes in an SQL query are for values, so MySQL isn't interpreting this as you expect. If you want to use quotes for a column (or table) name, you need to use backticks:
$sql = "SELECT test1,`$montreal` AS testX FROM test WHERE test1='$zurich'";
Will work. Though as you noticed, you can get the same effect by omitting any quotes.
This is invalid PHP Code:
'$montreal'
Single quotes will not process variables inside of them. Change it to double quotes:
$row["$montreal"]
Or, better yet, remove the quotes all together:
$row[$montreal]
Read more here:
What is the difference between single-quoted and double-quoted strings in PHP?

Implement data using query

I want to create a php page that contains a html drop down list of people's names (as the option
text) and then their age (as the value). Below is my form for you to see (almost what I mean) which I hard coded:
<form>
<select name="nameOption">
<option value="">Select your name:</option>
<option value="45">Mary Smith</option>
<option value="16">Lily Roe</option>
<option value="32">Elliot Perkins</option>
</select>
<p><input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Reset" />
</form>
What I want to do (or been trying to do) is to create the drop down list by running a SQL query to obtain the data (the people's name and age) from my database (unlike what I written above) and then when I click on one of the options, only their value or age should appear. So basically, I need to implement the data from the database into a drop down list
Now it's here where I am stuck. I am familiar with writing SQL statements for tables but I seem to get puzzled when I try to create a SQL statement for a drop down list in a php tag.
How would I write it? Like:
$sql = "SELECT name, age FROM person WHERE name = ". $person. ";
or
$nameOption = $_POST['nameOption'];
print_r ($nameOption);
with selecting a database:
$conn = mysql_connect("localhost", " ", " ");
mysql_select_db(" ", $conn)
I know it may seem like a dull answer but I need help. How would I implement SQL query to a drop down list? I would love your help.
As you have to enclose string in quotes, change your query to
$sql = "SELECT name, age FROM person WHERE name = '$person'";
and for showing dropdown dynamically you can do like
$query=mysql_query($sql);
echo '<select name="nameOption">
<option value="">Select your name:</option>';
while($result=mysql_fetch_array($query))
{
echo '<option value="'.$result['age'].'">'.$result['name'].'</option>';
}
echo '</select>';
You should do like that
<select name="nameOption">
<?php
$query = mysql_query($sql);
while( $row = mysql_fetch_array($query) ) {
echo '<option value="'.$row['age'].'">"'.$row['name'].'"</option>';
}
?>
</select>
You need to get the full list of people from the database first, then iterate through that outputting each option tag for each row:
$cnx = new Mysqli('localhost', 'username', 'password', 'database_name');
$people = $cnx->query("SELECT name, age FROM person");
echo '<select name="nameOption">';
while($person = $people->fetch_assoc())
{
echo '<option value="' . $person['age'] . '">' . $person['name'] . '</option>';
}
echo '</select>';

Displaying Option Values From Concatenation In PHP Echo

hit a wall on what should be a non-issue. Have a PHP echo with two concatenations in them to populate option values for a pull-down menu in a form, with the data for the option values being pulled from a MySQL database query. Works great, except that for some reason the option value will ONLY display the first word, and when it encounters a space in the value it drops it out of the option value field and populates the second, third words prior to the option value.
Here's the code:
<td width="160"><p> Job Location:</p><select class="listmedium" id="JobLocation" name="JobLocation"><option value='' selected="selected"></option>
<?php
$con = mysql_connect("Values Deleted");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db ("database1", $con);
$result = mysql_query("SELECT CustomerLoc FROM customerloc ORDER BY CustomerLoc ASC");
while($row = mysql_fetch_array($result))
{echo "<option value=" . $row['CustomerLoc'] . ">" . $row['CustomerLoc'] ."</option>";}
mysql_close($con); ?>
</select>
Which outputs as:
<td width="160">
<p> Job Location:</p>
<select id="JobLocation" class="listmedium" name="JobLocation">
<option selected="selected" value=""></option>
<option springs="" value="Carrizo">Carrizo Springs</option>
<option wells="" value="Artesia">Artesia Wells</option>
</select>
Notice the "springs" and "wells" place themselves BEFORE the option value quotes where the concantenation is intended to place the entire value, which should read "Carrizo Springs" and "Artesia Wells" for the option values.
Now, if I insert a &nbsp manually between the values, the entire value shows up as "Carrizo&nbspSprings" and works (but I don't want to insert &nbsp in each if I don't have to) and also if I manually code the HTML values to read "Carrizo Springs" it then works fine as an option value, thus it seems to be something happening with the PHP data call.
I know it is not ideal to use text in place of integers in option values, but there is a reason behind it, and I would appreciate any help from ya'll if someone knows why the PHP would display the output in that manner.
The problem is this row:
"<option value=" . $row['CustomerLoc'] . ">"
it becoming to <option value=Carrizo Springs >
so it is like value=Carrizo ,to solve this just change to this:
"<option value=\"" . $row['CustomerLoc'] . "\">"

set default drop down value on php generated form

I generated a drop down menu with the code below. How can I set the field to the GET variable after submit is clicked?
<select>
<?php
$sql="SELECT c FROM problems WHERE b='$id'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["c"];
$c=$row["c"];
$options.="<option value=\"$id\">".$c;
}
?>
<option value=''>C <?=$options?> </option>
</select>
<select>
<?php
$sql="SELECT c FROM problems WHERE b='$id'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["c"];
$c=$row["c"];
if($_GET['var'] == $id)
echo '<option selected="selected" value=\"$id\">' . $c . '</option>';
else
echo '<option value=\"$id\">' . $c . '</option>';
}
?>
</select>
Basic idea is compare value GET data with database data and using if else condition add selected="selected" if condition matched. I am directly printing string as they will not be getting use later on.
I'm a bit confused about what you want to know. To have an option selected by default, use the selected="selected" attribute on that option.
If you want to know how to get the submitted value in PHP, you need to assign the name attribute to the <select> tag. In general, however, you've got the idea right.

Categories