Pulling a blank result - php

I have not found a solution to prevent this. I am using PHP to self populate my option fields so I don't have to manually add them all in. I have four select fields and three out of the four work perfect but the fourth one.
On the company field it will populate one blank field and then it populates the rest just fine. I have a solution for this that will remove this space but I was informed that it is not the best practice. Anyone think they know a better and more correct way of achieving this?
PHP Select Field
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php include 'datalogin.php'; // Populates the Company select field
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) { //The empty if is to remove the blank space in the select field
}
else {
echo '<option value="'.urlencode($row['Company']).'">'.htmlspecialchars($row['Company'],ENT_QUOTES).'</option>';
}
}
?>
</select>
Ideally I was told you should use "!" to tell the if statement to echo if it is not null but it still produces the blank space:
if ($row['Company'] !== NULL) {
echo '<option value="'.urlencode($row['Company']).'">'.htmlspecialchars($row['Company'],ENT_QUOTES).'</option>';
}
This is what I mean by the blank space:
(Pretend it is a select field)
[Select a field]
[ ]
[Cleveland ]
[Columbus ]
[Toldeo ]
Live Agent Search Site

SELECT DISTINCT Company
FROM `roster`
WHERE LENGTH(Company) > 0
ORDER BY Company ASC;

Related

Displaying form selected option results from database

Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.

Php mysqli Listbox

I have a list box and have 2 questions.
1st how can i still have the text to say Select a country?
2nd on my update page it displays the proper country but will not allow it to be change for it will not list any of the other countries in edit page
<?php
$sql = "SELECT countries.country_id, countries.country_name, users.user_country FROM countries, users
WHERE users.user_country = countries.country_id";
$result = query($sql);
?>
<select class="form-control input-lg box" id="country" name="country">
<?php
$i = 0;
while (($row = mysqli_fetch_assoc($result)) != false) {
?>
<option value="<?=$row["country_id"];?>"><?=$row["country_name"];?></option>
<?php
$i ++;
}
?>
Well, to have a default option not provided by your database call, you just need an HTML statement such as
<option value="">Select a country</option>
right below your <select> statement.
And we can't see your table definitions, but your SQL code seems to be picking the specific country that the user is associated with, so that there is only one country in the list. You probably need two queries: One that obtains the user's current country, and a second that obtains the entire list of countries.
After the first query, save the user's current countryid in a variable - say, $usercountryID.
Then, in your loop through the countries, compare each countryID to the user's country, like this:
while (($row = mysqli_fetch_assoc($result)) != false) {
if ($usercountryID == $row["country_id"]) $selected = " selected";
else $selected = "";
echo "<option value='{$row['country_id']}$selected>{$row['country_name']}</option>\n";
}
$selected could be defined many ways, of course, including in a conditional assignment statement. I omitted the $i counter, which isn't needed here, but, of course, you might need it later.

set variable as first option in array php mysql

I have a select box being filled in with a mysql query, it functions fine and is selectable. Data changes and works fine.
It currently sorts based on the branch_id column and what I want is the session variable of $branch_id to be the first option of the select box. This is based on the branch selected from a previous page.
This is where I am stuck.
Here is some sample code of the branch dropdown.
This selection then changes a list of users that appears in an options box below this code. It all functions fine, I just need to refine it so the currently selected branch(from a prev page) is the first in the branch dropdown.
If anyone can help I'd really appreciate it.
//get list of allowed Branchs
$AllowBranch = "SELECT branch_id FROM access WHERE userid IN (SELECT id FROM user WHERE username = '{$_SESSION['user']}') ORDER BY branch_id ASC";
$getAllowBranch = mysql_query($AllowBranch);
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<OPTION VALUE = '{$getAllowBranchRow['branch_id']}' "; if($NeedBranch == $getAllowBranchRow['branch_id']) { echo "selected"; } echo "> ".ucwords(strtolower($Namerow['name']));
}
echo "</SELECT>";
Check the source code to see if the selected attribute is put in the right option tag. Also, you forgot to close every <option> tag with a </option>, not sure, but this could also be the problem.
First of all, you have missing tag <select name="<your field name>"> before while loop.
Then you have missing closing tag </option> too. You cannot solve your problem, if you have HTML broken.
So, it should looks like this:
echo '<select name="<your field name>">';
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<option value='" . $getAllowBranchRow['branch_id'] . "'" . $NeedBranch == $getAllowBranchRow['branch_id'] ? " selected" : "" . ">" . ucwords(strtolower($Namerow['name'])) . "</option>";
}
echo "</select>";
What I have done?
Firstly, I fixed your missing HTML tags. Then I just simply used ternary operator to check if branch_id equals to $NeedBrach and if yes, add following string selected and if not, add nothing.
Don't forget to replace <your field name> with your expect select name.
Important final thoughts!
I have to remind using mysql_* is deprecated, you should use mysqli_* or PDO instead with prepared statements.

Search query with newline for textarea data

i was using a input tag for entering the address in the form.
Input form code :
<input type="text" name="address">
and the search query for searching the addresses, worked without any problem
Search form code:
<input type="hidden" name="category_address" value="address"/>
<select name='criteria_address'">
<option selected="selected"> </option>
<?php
$order = "SELECT DISTINCT address FROM lh_clients ORDER BY clientname" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[address] </option>");
}
?>
Search Result Display code :
if(isset($_POST['criteria_address']))
{
$category_address = $_POST['category_address'];
$criteria_address = $_POST['criteria_address'];
$query = "SELECT * FROM lh_clients WHERE $category_address LIKE '%".$criteria_address."%'";
echo "<tr><td colspan='8'>$num_rows Results Found</td></tr>";
while($data = mysql_fetch_array($result))
{
echo("<tr>
<td>$data[clientname]</td>
<td>$data[clienttype]</td>
<td>$data[address]</td>
<td>$data[contacts]</td>
<td>$data[sensitivity]</td>
<td>$data[acountmanager]</td>
<td>$data[responsibleexecutive]</td>
</tr>");
}
But now when i replacing the input tag and using tag instead of it
textarea code :
<textarea name="address"></textarea>
The Search code doesn't work. The tag works fine, it pop up data from the address column but doesn't providing any search result according to that address.
By the way, when i give input something with out entering newline it works.
If any one can understand my problem please reply.
Thanks a lot in advance.
if you put a newline in your searchword, you only gettings rows with that have that newline stored in the database.
1.
if an adress is stored in the database like
"street 1, 123 45 town",
and you try to search it by writing
"street 1
123 45 town"
they not going to match, you may want to replace newlines with % to allow other seperators.
2.
if you adress is stored in the database like street 1, and your search for
"street 1
"
then you may want to use trim() on the searchword to get rid of extra newlines
3.
to avoid carage return problem, you can use REPLACE
SELECT *
FROM lh_clients
WHERE
REPLACE(adress, '\r', '') LIKE CONCAT('%', REPLACE(:adress, '\r', ''), '%');
where :adress should be bind/replaced with the input variable

php get user dropdown selected

how do i get dropdown selected for each user.
user table
------------
id job
1 1
2 2
job table
----------
id name
1 Doctor
2 Sales
$q = $db->query("SELECT * FROM affiliate LEFT JOIN user ON user.job = affiliate.id_affiliate");
while($r = $q->fetch_array()) :
if($r['id_user'] == $_SESSION['id_user'] && $r['job'] == $r['id_affiliate']) {
echo '<option selected value="'.$r['id_affiliate'].'">'.$r['org'].'</option>';
} else {
echo '<option value="'.$r['id_affiliate'].'">'.$r['org'].'</option>';
}
endwhile;
selected="selected" or just selected should normally work. If not there is a problem with your if statement. One simple way is to echo out the content of the if statement like this:
note!! the echo should normally be done outside the select open tag, just paste the following outside the select open tag but just after your query.
while($r = $q->fetch_array()) :
echo $r['id_user'] .'=='. $_SESSION['id_user'] .'&&'. $r['job'] .'== '.$r['id_affiliate'].'<br />';
endwhile;
you can now check if the values actually match. if not then there is your problem.
How about modifying the following ...
if( ($r['id_user'] == $_SESSION['id_user']) && ($r['job'] == $r['id_affiliate']) )
Not sure if it matters, but I have selected at the end of my option.
<option value='cat' selected>

Categories