Issue with ternary operator in echo - php

I'm having this following piece of code which populates a dropdown box based on the country column in my database. This works perfectly fine.
echo "<select name='pob_country' id='pob_country' data-native-menu='false'>";
echo "<option>Country</option>";
while ($row_country = mysql_fetch_array($result_countries)) {
echo "<option value='".
$row_country['country'] ."'>".
$row_country['country'] .
"</option>";
}
echo "</select>";
Now I want to set one <option> to selected based on a variable.
I tried it with a tenary operator, like so:
echo "<select name='pob_country' id='pob_country' data-native-menu='false'>";
echo "<option>Country</option>";
while ($row_country = mysql_fetch_array($result_countries)) {
echo "<option value='".
$row_country['country'] ."'".
(($pob_country=="$row_country['country']") ? "selected" : "") .
">".
$row_country['country'] .
"</option>";
}
echo "</select>";
Somehow this doesn't work, the page doesn't load.
I don't understand what I'm doing wrong here.
It probably is something really simple but I'm stuck on it for over an hour.
Any help is appreciated.

Remove the quotes:
($pob_country==$row_country['country'])

Related

PHP drop down selection

I've set up a php form that registers a project to our database, it has a drop down that populates from our customer/supplier databases.
I've also set up a function to edit these projects, the problem I have is that when I go to my edit page it just displays the customer/supplier name and not in the drop down but a value box - is there a way to have the edit page display the dropdown but also be selected on the original supplier/customer?
Register project page
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo '<select name='client'>';
while($row = mysql_fetch_assoc($result))
{ `
echo '<option value = ''.$row[name].''>'.$row[name].'</option>';
}`
echo '</select>';
?>
Edit page
<input type='text' name='client' value='<?php echo $client; ?>'/>
I tried a few tutorials and code tweaks but kept getting errors. I am aware of my sql injection problem, at the moment this site is internal.
Any help would be appreciated.
thanks
instead of $row[name] you should use $row['name']
$client= "<select name='client'>"; // you had error here also.
while($row = mysql_fetch_assoc($result))
{
$client.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
$client.= '</select>';
now echo $client to get dropdown.no need of constructing separate select tag now.
for selected use like this:
$client1= "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
if($row['name'] == $clientValue){
$client.= "<option selected='selected' value = '".$row['name']."'>'".$row['name'].'</option>';
}else{
$client1.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
}
$client1.= '</select>';
on echo of $client1 you will get selected based on the value $clientValue which you have to pass.
On your edit page:
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo "<select name=\"customer\">";
while($row = mysql_fetch_assoc($result))
{
if ($row['name'] == $client)
{
echo "<option selected value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
else
{
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
}
echo "</select>";
?>
I also suggest that you change the old extension for mysql. I can't see no SQL Injection problem for now, but you should take care of it even if it is internal, because, from different reasons you will forget to sanitize it later. If you are writing it, then write it correctly.
Now for the problem, you are not using the quotes correctly, hence the errors. Do not use the same type of quotes, but change them, like so:
echo '<select name="client">';
Or if you use double quotes for concatenation, use single inside.
In case you have to use the same, escape them with \
For starters, you have a syntax error here:
echo '<select name='client'>';
(There are probably more quoting errors throughout the code, but I digress...)
As for using a drop-down, what you're looking for is the selected attribute. When you're building the page elements to display the form on the "edit" page, presumably you have the values that you're looking to display. When your loop finds an element which matches the value, select it:
while($row = mysql_fetch_assoc($result))
{
if ($knownValue == $row[name]) {
echo '<option selected value = ''.$row["name"].''>'.$row["name"].'</option>';
} else {
echo '<option value = ''.$row["name"].''>'.$row["name"].'</option>';
}
}

how to get listbox value in another php page

i think i am doing some mistake in my code. can someone please correct me. how to get the list box values in another page.
print "<form method=\"post\" action=\"fetch_test.php\">";
print "Report From: ";
print "<select name=fromdate[]>";
print "<option selected=\"selected\">Date</option>";
print "<option value=01>01</option>";
print "<option value=02>02</option>";
print "<option value=03>03</option>";
print "</select>";
print "<select name=frommonth[]>";
print "<option selected=\"selected\">Month</option>";
print "<option value=jan>Jan</option>";
print "<option value=feb>Feb</option>";
print "<option value=mar>Mar</option>";
print "</select>";
print "<br><br>";
print "<input type=submit>";
print "</form>";
fetch_test.php contains below code.
<?php
print $_POST['fromdate'];
print $_POST['frommonth'];
?>
You are using the name as an Array.
Fixed code:
print "<form method=\"post\" action=\"fetch_test.php\">";
print "Report From: ";
print "<select name=fromdate>";
print "<option selected=\"selected\">Date</option>";
print "<option value=01>01</option>";
print "<option value=02>02</option>";
print "<option value=03>03</option>";
print "</select>";
print "<select name=frommonth>";
print "<option selected=\"selected\">Month</option>";
print "<option value=jan>Jan</option>";
print "<option value=feb>Feb</option>";
print "<option value=mar>Mar</option>";
print "</select>";
print "<br><br>";
print "<input type=submit>";
print "</form>";
You stored it in an array, so call it in an array also.
<?php
print $_POST['fromdate'][$yournumbervalue];
print $_POST['frommonth'][$yournumbervalue];
?>
Try quoting your select tag names, you want to have <select name="fromdate[]"> to get an array, and you want to use <select from="fromdate"> to get a single value.
Unless there are more than one name='fromdate' or name='frommonth', you don't need the [].
Just try normal:
print "<select name='fromdate'>";
Make sure you put ' around the name attribute!
Then use:
$_POST['fromdate'];
At the moment you're putting it into an array, so if you want to keep it the way it is, use:
foreach ($fromdate as $date){
echo $date;
}

Issue with PHP variable when fetched from MySQL

I have a variable like "Doctor and Surgical" I take this value from Mysql database and store it in a variable. When I echo this variable it gives me only "Doctor"
Can anyone tell me how can I take the above value retrieved from Mysql as an entire variable...
EDIT
Please find the code below
query.php
<form action="process.php" method="post">
<select name="cat">
<?php
$sql="select distinct Category from tbl_1 order by Category asc";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query))
{
echo "<option value=".$row[Category].">".$row[Category]."</option>";
}
?>
</select>
<select name="station">
<?php
$sql_1="select distinct Station from tbl_1 order by Station asc";
$query_1=mysql_query($sql_1);
while($row=mysql_fetch_array($query_1))
{
echo "<option value=".$row[Station].">".$row[Station]."</option>";
}
?>
</select>
<input name="C" type="submit" />
</form>
process.php
$myValue =$_POST['cat'];
$myStation=$_POST['station'];
echo $myValue;
echo "<br/>";
echo $myStation;
$mySqlStm ="SELECT Name FROM tbl_1 WHERE Category='$myValue' and Station='$myStation'";
$result2 = mysql_query($mySqlStm) or die("Error:mysql_error()");
if(mysql_num_rows($result2) == 0){
echo("<br/>no records found");
}
ELSE
{
echo "<table border='1'>";
//ECHO THE RECORDS FETCHED
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
}}
Here when I echo $myValue it gives me "Doctor" instead of "Doctor and Surgeon"
I need "Doctor and Surgeon as an entire variable.
You need to quote the value properly:
echo "<option value='".$row[Category]."'>".$row[Category]."</option>";
With your current code, if you look at the source you will probably see something like this:
<option value=Some Category>Some Category</option>
But with proper quotation you'll see the correct value.
You can use this without having to concatenate:
echo "<option value='{$row[Category]}'>{$row[Category]}</option>";
Think of the quotes just like you would a bracket or an html tag. When you open one, you are inside until you close it. In this case, you needs quotes to tell php what to echo out and different quotes that will print for html attributes. It's usually easier to use single quotes for the php echo commands and double quotes for the html code. Then the . just means to stitch a bunch of stuff together without having to put the echo command ten times in a row. So when you have this:
echo '<option value="'.$row[Category].'">'.$row[Category].'</option>';
you can break it down like this (just for your mental clarity, don't actually code this):
echo
'<option value=" '
.
$row[Category]
.
' "> '
.
$row[Category]
.
'</option>'
;
Use single quotes & Just insure the value of $row['Category']
Try it:
echo "".$row['Category']."";

Why is my loop producing empty <option></option> tags in my <select>?

I have the following code:
<?php
$a= 11;
echo "<select name='rabboSelect' style='width:300px;'>";
$sqlQuery="SELECT * FROM writers";
$result=sql($sqlQuery);
while($row = mysql_fetch_array($result))
{
$a .= "<option value='" .$row["ID"]."'>" . $row["name"] . "<option>";
}
echo str_replace("<option></option>", "", $a);;
echo "</select>";
?>
and in the html it's adding <option></option> after each one, even if I try to delete it:
<select name="rabboSelect" style="width:300px;">11<option value="2">הרב מילר</option><option></option><option value="3">משה דוויד</option><option></option><option value="4">קלמי גריינמן</option><option></option><option value="5">בנימין יעבץ</option><option></option><option value="8">אליהו פרץ</option><option></option></select>
How can I stop this from happening?
Firstly, I wonder why you are setting $a=11; - did you maybe mean $a='';?
Next, you are missing a / in the closing option tag. If you tried View Source rather than viewing the DOM, you'd see that rather than the extra options.

Pre-filling select tags from array

I've got this array:
$profession_type = array(
'Professional Engineers',
'Accountants',
'Insurance Professionals',
'Attorneys',
'Certified Hazardous Materials Managers',
'Safety Professional',
'Industrial Hygienists',
'IT Professionals',
'Human Resource'
);
I am display the contents of the array as the options for the select tag:
<select name="profession_type[]">
<option value=""></option>
EOL;
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
print <<<EOL
</select>
I've never pre-filled a drop down box with dynamic values. The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.
EDIT: Sorry my question was unclear.
The user will select a value from a previous screen (say it's called id) and hit submit.
Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the id they selected.
The values that the stored procedures returns will prefill the "profession_type[]" form field.
I would like the <option value='accountants' selected>Accountants</option> if the stored procedure returns "Accountants" for the value of "profession_type" based on the id.
Is that more clear? Sorry.
Any suggestions?
How about this:
print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
if ($p == $chosen_profession)
print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
else
print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';
This goes in your .php file:
<!-- some HTML here -->
<?php
$profession_type = [result_from_database_query] ?>
<!-- more HTML here -->
<select name="profession_type">
<?php
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
?>
</select>

Categories