How to make <option selected="selected"> set by MySQL and PHP? - php

How to make <option selected="selected"> set by MySQL and PHP?
My code:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
//if($year==$r["year"]){ $selected=' selected="selected"'; }//doesn't work so
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option>".$r["year"]."</option>";//<option$selected>...
}
}
unset($tempholder);
echo '</select>';

Try this one:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option".(($year==$r["year"])? ' selected="selected"' : '').">".$r["year"]."</option>";
}
}
unset($tempholder);
echo '</select>';
It doesn't saves the state in a variable which you have to overwrite.
And I think the real error was the single equal sign in $year=$r["year"] and not wihtin the rest of the code.

In addition to fixing the =/== gotcha, you can save yourself the array lookup and make the code simpler by asking the database to return each year only once in the query:
<select>
<?php $result= mysql_query('SELECT DISTINCT year FROM id ORDER BY year'); ?>
<?php while($row= mysql_fetch_assoc($result)) { ?>
<option <?php if ($row['year']==$year) { ?>selected="selected"<?php } ?>>
<?php echo htmlspecialchars($row['year']); ?>
</option>
<?php } ?>
</select>
(You may not need htmlspecialchars() assuming that's a numeric year, but it's good practice always to HTML-escape any plain text you include in an HTML template. You can define a function with a shorter name to do the echo htmlspecialchars to cut down on typing.
)

You must define $selected everytime, and you were using the assignment operator instead of the comparison:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i = 0; $i < $nr; $i++){
if($year == $r["year"]) { //not $year = $r["year"]
$selected=' selected="selected"';
}
else {
$selected = "";
}
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option$selected>" . $r["year"] . "</option>";
}
}
unset($tempholder);
echo '</select>';

Adding a new answer here for posterity, since the old code, which while correct at the time (actually mysqli did exist, but many hosts didn't support PHP 5), is unfortunately using deprecated code. Instead of using mysql_ extensions, here's a way to handle it using an object oriented approach which will work with mysqli_ connections:
Here's the database connection
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Assuming that the $year variable is coming from a form (though it could be used from GET or SESSION or wherever)
$year = $_POST['year'];
Here's the query for the option button (I have it broken out into different rows to make it a little easier to read):
$result=$conn->query($sql);
while($row = $result->fetch_assoc()) {
if ($row['year']==$year) {
$selected = 'selected="selected"';
}
else {
$selected = '';
}
echo '<option value="'.$row['year'].'" '. $selected . '>"'
. $row['year'] .'</option>';
}

Related

Populating a Dropdown Selection from MySql & Php [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
Hopefully this question doesn't drive anyone to drink.
I've been at this for about 9 hours now and cannot get a drop down to populate. I know I'm missing something very simple and I'm reaching out to see if anyone can give me some insight. The table I'm calling from has 1 column and just has names (which are unique)
I have a db class being called in the beginning of all of my pages, in all but 2 cases , its working fine, in the 2 exceptions, it's the pages that require the dropdown. I've deleted and recreated both pages with no change.
Both Pages are named select.php and select_p.php. The initial call is as follows and breaks at the first "->" so begins printing everything after it and up until the "?>"
include("database.class.php");
$database = new database;
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
?>
Heres the fucntion in the class file that works on 2 other sites and other pages in this same site
function mysqlQuery($qry)
{
$rs = mysql_query($qry, $this->DatabaseLink);
return $rs;
echo mysql_error();
}
Now if I use the code in the page, it doesnt print but the dropdown is blank
<select name='list' value=''><option>Select List</option>
<?
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
foreach($edata_page as $row){
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
I've looked at the following (plus about 20 pages that are not this close)
PHP- Fetch from database and store in drop down menu html
How to put table value in a dropdown menu with MYSQL and PHP
http://www.plus2net.com/php_tutorial/list-table.php
http://www.tutorialrepublic.com/faq/how-to-populate-dropdown-list-with-array-values-in-php.php
Here's all the snippets of code I've tried to no avail, some of them actually print the code in the html form, any constructive help would be very much appreciated.
*********************************************************
<select name='list' value=''><option>Select List</option>
<?
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
foreach($edata_page as $row){
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
*****************************************************************
<select name='list' value=''><option>Select List</option>
<?
$result = $database->mysqlQuery("select * from spec_tables");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$row = array();
for ($i = 0; $i < $num_fields; $i++)
while ($row = mysql_fetch_row($result))
{
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
********************************************************************
<select name='list' value=''><option>Select List</option>
<?
$result = $database->mysqlQuery("select * from spec_tables");
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value=". $row['name'] .">' . $row['name'] . '</option>';
}
}
?>
</select>
****************************************************************************
Placed in top of file
$servername = "localhost";
$username = "uname";
$password = "pword";
$dbname = "db_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($result = mysqli->query("SELECT * FROM 'spec_tables'")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
**********************************************************************
<?
$sql = "select * from spec_tables";
$result = mysql_query($sql);
echo "<select name='list' value=''><option>Select List</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo "</select>";
?>
**************************************************
Heres the code thats working
//placed in beginning of code
<?php
include("database.class.php");
$database = new Database;
$result = $database->mysqlQuery("SELECT * FROM spec_tables");
?>
//Placed inside html form
<?php
echo '<select name="list">';
echo '<option>Select List</option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['name'] .'">' . $row['name'] .'</option>';
}
echo '</select>';
?>

Populate multi-select with php while loop from db

The following worked on a local environment. Now that it's pushed
live everything but these seems to work. Displays completely empty select boxes now no checks or blank labels just empty space in the "select options" drop down.
select display
<?php
$selected = array();
$selected = explode(",",$fill['markets']);
$condb = mysql_query("SELECT * FROM `countries`");
$count = mysql_num_rows($condb);
$countries = array();
$str;
while ($countries = mysql_fetch_array($condb))
{
$str = "option{$countries['id']}";
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
}
?>
You should use while loop instead. You can declare $i outside the loop if you need it, Try the following code:
$condb = mysql_query("SELECT * FROM `countries`");
$i = 0;
while($countries = mysql_fetch_array($condb)) {
$str = 'option' . $i;
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
$i++;
}
?>
</select>
Note:
mysql_* is deprecated as of php-5.5. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

How to display certain rows from mysql with variable sent via HTML form

I'm trying to get certain data which meets the criteria from the database using AND condition with user searchable HTML form which sends the data to the search.
Code:
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
if (isset($_POST['Kohderyhmä']) &&
isset($_POST['Näytön aste']) &&
isset($_POST['Vaikutusten vahvuus']) &&
isset($_POST['Käyttökelpoisuus']) &&
isset($_POST['text']))
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
$Näytön_aste = get_post($conn, 'Näytön aste');
$Vaikutusten_vahvuus = get_post($conn, 'Vaikutusten vahvuus');
$Käyttökelpoisuus = get_post($conn, 'Käyttökelpoisuus');
$text = get_post($conn, 'text');
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='$Kohderyhmä' AND `Näytön aste`='$Näytön_aste' AND `Vaikutusten vahvuus`='$Vaikutusten_vahvuus' AND `Käyttökelpoisuus: luokka`='$Käyttökelpoisuus'";
}
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
echo '<h3>' . $row['Nimi'] . '</h3><br />';
echo '' . $row['Kokonaisarvio'] . '<br />';
echo '' . $row['Kuvaus'] . '<br /><br />';
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<b>Kohderyhmä</b><br />
<select name="Kohderyhmä" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Pikkulapset">Pikkulapset</option>
<option value="Alle kouluikäiset">Alle kouluikäiset</option>
<option value="Alakouluikäiset">Alakouluikäiset</option>
<option value="Nuoret">Nuoret</option>
<option value="Perheet">Perheet</option>
<option value="Vanhemmat">Vanhemmat</option>
<option value="Työntekijät">Työntekijät</option>
</select>
<br />
<b>Näytön aste</b>
<select name="Näytön aste" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei riittävää näyttöä">Ei riittävää näyttöä</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Vaikutusten vahvuus</b>
<select name="Vaikutusten vahvuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei vaikutusta">Ei vaikutusta</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Käyttökelpoisuus</b>
<select name="Käyttökelpoisuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei käyttökelpoinen">Ei käyttökelpoinen</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<br />
Haku: <input type="text" name="text" />
<input type="submit" value="Hae" />
</form>
I haven't used PHP to contact database before so the PHP code is very messy.
I don't understand any more than the very basics from PHP, I haven't used variables or objects or anything complex before.
HTML form:
variable1
variable2
variable3
variable4
variable5
--->
PHP script:
select * from db
where variable1 and variable2 and variable3 and variable4
--->
display results matching the criteria
Current code causes this error message in error_log:
PHP Warning: mysqli::query(): Empty query in /home/user/public_html/folder/script.php on line 23
I have already tried over 15 different variations of variables and sql query in total and nothing has worked..
If we shorten your if (isset($_POST ... something you can clearly see. This instruction
$results = $conn->query($query);
is always executed, regardless of whether isset returns true or not.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
}
$results = $conn->query($query);
So if only one field has not been filled out correctly, the error is always the same :
PHP Warning: mysqli::query(): Empty query in ....
This makes it difficult to determine where the fault really comes from.
Place the curly bracket } behind database logic.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
....
}
}
?>
create a short test program to test only the database. Set only really necessary data fields in the query
test.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$Kohderyhmä = "KohderyTest"; // replace with really existing values
$query = "SELECT * FROM `tietokanta` WHERE Kohderyhmä='".$Kohderyhmä."' ";
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
$results->free();
?>
Add hardcoded variables $Näytön_aste = "reallyExistingValue"; , add query data field for data field and watch when it starts to stutter.
Also we can not see your function get_post()
If you mean the Wordpress function get_post(), your call to the function is wrong.
I can well imagine that the failure from the function get_post() comes.
And you always false or empty values assigns.
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
assign it direct.
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
...)
{
$Kohderyhmä = $post['Kohderyhmä'];
...
Also you are using all select fields from the <form>, in the query.
4 Select's with 8,6,6,6 options means
8x6x6x6 == 1728
1728 possibilities are you shure you have one datarecord where all values matches.
WHERE Ko...='$Ko...' AND `Näy...`='$Näy...' AND `Vai...`='$Vai...' AND `Käy...`='$Käy...'";
WHERE All four Datafields must match to get a result !!!!!!!!!!!!!
You have to find a combination where all four values simultaneously exist.
UPDATE
OP new question :
If you want empty or some named values stop searching for a value in
database.
required every single variable to be found in the database which it
didn't find because I couldn't set the variable and there is no value
for "Kaikki" in the database, the word "Kaikki" means all choices
below that choice in the HTML form and for that I need some PHP
Here comes the new test.php
1) don't do $post['Näytön aste']; In the form the name is
<select name="Näytön aste" style="...">.
This will translated by submit to
$post['Näytön_aste']; look at the underscore _
This must be done with all select name with spaces in the name !!
2) That was the reason why you get not all $_POST[....] values !
OK ?
3) replace in your form
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
with
<form action="testNew.php" method="POST">
testNew.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
} else { die ("No valid values"); }
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Kohderyhmä`= '".$Kohderyhmä."'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste`= '".$Näytön_aste."'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus`= '".$Vaikutusten_vahvuus."'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus: luokka`= '".$Käyttökelpoisuus."'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
} else {
echo "with your choices no records were found";
}
$results->free();
?>
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='{$Kohderyhmä}' AND `Näytön aste`='{$Näytön_aste}' AND `Vaikutusten vahvuus`='{$Vaikutusten_vahvuus}' AND `Käyttökelpoisuus: luokka`='{$Käyttökelpoisuus}'";
Replace your query with this, and try.

How can I write html in while inside php using fetch_array data?

I tried many things but i just cant make the value of option an id from database and i cant write the option as date and title from database
im doing this so far, any help would be appreciated.
<select name="agenda "size="10">
<?php
global $connection;
$result = mysql_query("SELECT * FROM agenda where date > now() order by date", $connection);
$i = 0;
while ($row = mysql_fetch_array($result) && $i < 20)
{
$id = $row['id_agenda'];
$date = $row['date'];
$title = $row['title'];
//here i would like to make an option with
//value = id_agenda and write the date_agenda and title_agenda
//something like this
//<option value="$row[$id]">$date $title</option>
$i++;
}
?>
<option value="Google">meeting 2</option>
</select>
Use:
echo "<option value=\"$id\">$date $title</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value=\"$row[id_agenda]\">$row[date] $row[title]</option>";
}

php - auto select drop down menu based on parameters in browser link

If in the browser I have parameters like:
http://localhost/specials.php?year=2009&make=honda&model=civic
and the dropdown looks something like this:
<select name="year">
<?php
$query = mysql_query("select distinct year from tbl_content where year = '$year'");
while($row = mysql_fetch_assoc($query)) {
echo "<option value=\"{$row['year']}\">{$row['year']}</option>";
}
?>
</select>
Now what I'm trying to do is show select when the dropdown options value is equal to the parameter year in the browser URL.
I tried this:
<select name="year">
<?php
$query = mysql_query("select * from tbl_year
while($row = mysql_fetch_assoc($query)) {
#=============================
if(isset($_GET['year'])) {
$year = (int)$_GET['year'];
if($year == $row['year'] { $selected = "selected"; }
else { $selected = "";
}
echo "<option value=\"{$row['year']}\" {$selected}>{$row['year']}</option>";
}
?>
</select>
Maybe try "selected='selected'" to make it valid xml.
<select name="year">
<?php
$selectedYear = NULL;
if(isset($_GET['year']))
$selectedYear = (int)$_GET['year'];
$query = mysql_query('SELECT year FROM tbl_year GROUP BY year ORDER BY year ASC');
while($row = mysql_fetch_assoc($query)) {
echo '<option value="' . htmlspecialchars($row['year']) . '"';
if($selectedYear === (int)$row['year']) {
echo ' selected="selected"';
}
echo '>' . htmlspecialchars($row['year']) . '</option>";
}
?>
</select>
Fell free to separate functionality!
<?php
function selectList($name,$values,$labels=null,$selected=null){
if($labels==null) $labels=&$values;
$data="<select name='$name'>";
foreach($values as $k=>$v){
$selected=($v==$selected)?'selected="selected"':false;
$data.="<option value='$v' $selected>".htmlspecialchars($labels[$k])."</option>";
}
$data.="</select>";
return $data;
}
$select=isset($_REQUEST['year'])?(int) $_REQUEST['year']:null;
$query=mysql_query("SELECT DISTINCT `year` FROM `tbl_year` ORDER BY `year`");
while(($row=mysql_fetch_assoc($query))!==false){
$values[]=$row['year'];
}
echo selectList("year",$values,null,$select);
?>

Categories