PHP how to send and receive multiple choice box - php

I need suggestion.
I have an list of position from database, displayed in table and in the last table row is an option to select "TAK" - YES and "NIE" - NO, please tell me is it possible and if it, how to send and receive it all selected to "TAK" fields at file wypozyczalnia.php
<form action='wypozyczalnia.php' method='post'>
<table width="1000px" align="center" border="1">
<tr>
<th width="250px">Tytuł</th>
<th width="250px">Autor</th>
<th width="300px">Opis</th>
<th width="200px">Dostępność</th>
</tr>
<?php
//sprawdzanie czy taka zmienna jest ustawiona w sesji, jest to dla nowo wchodzących na stronę
if(isset($_SESSION['blad'])) echo $_SESSION['blad'];
//wyświetlanie wyników gdy zmienna ile zwróciła przynajmniej 1 rząd
if ($ile>=1)
{
//pętle wyświetlająca wszystkie zwrócone z zapytania wpisy
for ($i = 1; $i <= $ile; $i++)
{
//pobranie rzędu jako tablicę asocjacyjną
$row = mysqli_fetch_assoc($rezultat);
//przypisanie każdej kolumny do odpowiedniej zmiennej
$title = $row['title'];
$author = $row['author'];
$description = $row['description'];
$available = $row['available'];
echo
"<tr>
<td> ".$title." </td>
<td> ".$author." </td>
<td> ".$description." </td>
<td>";
if($available==1)
{
echo "TAK";
}
else
{
echo "NIE";
}
"</td>
</tr>";
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true) && $available==1)
{
echo
"<select name='idksiazki[]' >
<option name='NIE'>NIE</option>
<option name='TAK'>TAK</option>
</select>";
}
}
}?>
</table>
<?php
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true))
{
echo "<br /> <input type='submit' name='zapis' value='wypożyczam'></form>";
}
?>
</form>

At the moment you have multiple forms - one per table row, so each <select is inside its own form. You can't submit multiple forms at once from a HTML page. Also your existing forms seem to be missing the </form> tag so they will be invalid anyway.
Therefore, to be able to submit all the <select values at the same time, you need a single form, which has the entire table contained within it.
For example:
<form action='wypozyczalnia.php' method='post'>
<table>
<?php
if ($ile>=1)
{
//pętle wyświetlająca wszystkie zwrócone z zapytania wpisy
for ($i = 1; $i <= $ile; $i++)
{
//pobranie rzędu jako tablicę asocjacyjną
$row = mysqli_fetch_assoc($rezultat);
//przypisanie każdej kolumny do odpowiedniej zmiennej
$title = $row['title'];
$author = $row['author'];
$description = $row['description'];
$available = $row['available'];
echo
"<tr>
<th> ".$title." </th>
<th> ".$author." </th>
<th> ".$description." </th>
<th>";
if($available==1)
{
echo "TAK";
}
else
{
echo "NIE";
}
"</th>";
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true) && $available==1)
{
echo "<th>
<select name='idksiazki[]' >
<option value=$i;>NIE</option>
<option value=$i;>TAK</option>
</select>
</th>";
}
echo "</tr>";
}
}
?>
</table>
</form>
P.S. A note about HTML semantics: <th> is mean to indicate a table heading, e.g. the title of a column, or the main heading within a row. It should not be used for every cell in your table. <td> is for normal table cells. If you wish to make the text bold, use CSS instead.

Related

Getting contents of dropdown from table and storing it in an array

I just want to get the contents of the dropdown and store it in array.
I am able to display the dropdown but it doesn't get the contents of what I selected.
echo '<br><br><br><br><br>
<div class="Table">
<table border="2pt solid black" align="left" cellpadding="2px" bordercolor=black>
<tr>
<td width = "7%">
<div align = "left"><b>BRAND NAME</div></b>
</td>
<td width = "7%">
<div align = "left"><b>INGREDIENT</div></b>
</td>
<td width = "3%">
<div align = "left"><b>QUANTITY</div></b>
</td>
<td width = "7%">
<div align = "left"><b>MEASUREMENT</div></b>
</td>
</tr>';
for ($x = 0; $x < sizeof($rowarray); $x++) {
$query = "select R.name AS RAWNAME, I.name AS INGREDIENTNAME, R.quantity AS RAWQUANTITY from rawmaterial R JOIN ingredient I ON R.ingredient_id = I.ingredient_id where R.rawmaterial_id='{$rowarray[$x]}'";
$res = mysqli_query($dbc, $query);
while ($fetch = mysqli_fetch_array($res, MYSQL_ASSOC)) {
echo "<tr>
<td width=\"7%\">
<div align=\"left\">{$fetch['RAWNAME']}</div>
</td>
<td width=\"3%\">
<div align=\"left\">{$fetch['INGREDIENTNAME']}</div>
</td>
<td width=\"3%\">
<div align=\"left\"><input type='name' name='quantity[]' placeholder={$fetch['RAWQUANTITY']}></input></div>
</td>
<td width=\"7%\">
<div align=\"left\">";
echo "<select name = 'measure'>";
$mesr = mysqli_query($dbc, 'select measure from measure_ref');
while ($row = mysqli_fetch_array($mesr, MYSQLI_ASSOC)) {
$mes = $row['measure'];
echo '<option value ='.$mes.'>'.$mes.'</option>';
}
echo "</select>";
echo "</div>";
echo "</td>";
echo "</tr>";
}
}
echo '</table></div>';
$messarray = array();
$mes = $_POST['measure'];
$row = array();
foreach ($mes as $row) {
array_push($messarray, $row);
}
Check below points.
Make sure your dropdown is within form
As you are creating multiple dropdown you should give name with '[]'(measure[]),like you have given to 'quantity[]'.

<td> not filling all the dynamic table HTML PHP MySQL

My table is not filling all the data i need. Is missing some columns be filled with form multiple. The column where the th is Renault need to be the same for all the rest are empty.
In next picture, you can see when i select options in dynamic selectbox multiple and submit, is only filling in the first column when the expectable is fill all the columns selected.
Next is the code where is giving the value of the select box multiple.
if ($consulta !=0) {
}//
else{
echo "";
}
#$s1= $_POST['s1'];
if( is_array($s1)){
while (list ($key, $val) = each ($s1)) {
}
}//
else{
echo "";
}
/////////////////
#$s2= $_POST['s2'];
if( is_array($s2)){
?>
Next is the code where data is filled in the html table. That line of code<td align=\"center\" bgcolor='FFFFFF'> need to be associate the result of: <?php echo "$key => $val1\n";?> to which form:
The result of <?php echo "$key => $val1\n";?>
0 => Renault 1 => Opel 2 => Mercedes 3 => Audi
The expected output is missing.
Renault
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Opel
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Mercedes
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
Audi
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
That is dynamic, will get the values from mysql database and i can select which i want.
There is all the table where is filled the data. Static and dynamic.
<table>
<tbody>
<tr>
<th>Parametro:</th>
<?php
while (list($key, $val1) = each ($s2)) {
?>
<th><?= htmlspecialchars($val1, ENT_HTML5 | ENT_COMPAT, 'UTF-8') ?></th>
<?php
echo "$key => $val1\n";
?>
<?php
}
?>
The values down of the Parametro:
{
echo("<tr>
<td align=\"center\" bgcolor='FFFFFF'>$utilizador</td>
<td align=\"center\" bgcolor='FFFFFF'>
<form onsubmit=\"return validate();\" id=\"teste\" method=\"post\" action=\"teste.php\">
");
Code from the form:
$con = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$dat_menuid = mysqli_query( $con,"SELECT * FROM menu WHERE menuId = '".$menuId."'" ) // ◄■ MENUIDs.
or die( mysqli_error($con) );
$con1 = mysqli_connect( "localhost","root","","teste" ); // ◄■ CONNECT TO DATABASE.
$idtem = mysqli_query($con1, "SELECT MAX(id_tem) as id_tem FROM tem")
or die( mysqli_error($con) );
// Print out result
while($row = $idtem->fetch_assoc())
$toEcho = $row["id_tem"];
//echo $toEcho;
$toEchosave = $toEcho + 1;
$_SESSION['myvar'] = $toEchosave;
$options = array( "0.00","0.05","0.10","0.15","0.20","0.25","0.30","0.35","0.40","0.45","0.50","0.55","0.60","0.65","0.70","0.75","0.80","0.85","0.90","0.95","1" ); // ◄■■ OPTIONS ARE STATIC (ALWAYS THE SAME).
while ( $row_menuid = mysqli_fetch_array( $dat_menuid ) ) // ◄■ DISPLAY <SELECT>s.
{ echo "<select class='sumselect' name='corp_resp&{$row_menuid['menuId']}&{$_SESSION['UtilizadorID']}&{$dateTime}&{$toEchosave}' multiple>"; // ◄■■ CORP_RESP&1,CORP_RESP&2.
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>
follow this code
<?php
$sql = "SELECT * FROM menu WHERE $id = menuIdPai ORDER BY menuId ";
$consulta = mysql_query($sql);
while ($mostrar = mysql_fetch_array($consulta)) {
$id = $mostrar['menuId'];
$utilizador = $mostrar['menuNome'];
?>
<tr>
<td align=\"center\" bgcolor='FFFFFF'>Test1</td>
<td align=\"center\" bgcolor='FFFFFF'>Test2</td>
<td align=\"center\" bgcolor='FFFFFF'>Test3</td>
<td align=\"center\" bgcolor='FFFFFF'>Test4</td>
</tr>
<?php
}
?>
this is main format if work then update your code . you add 2 td but your main th 4 so need 4 td
your this tag not close
<td align="center" bgcolor='FFFFFF'>
<form onsubmit="return validate();" id="teste" method="post" action="teste.php">
so close this in your script
<div id='sum'></div>
<br><br><br>
</form>
</td>
</tr>
move this code before end loop
foreach ($options as $opt)
echo "<option value='$opt'>$opt</option>\n";
echo "</select>\n";
} ?>
</form>
</td>
</tr>
<?php } ?>
<?php }
}
}
?>
<div id='sum'></div>
<br><br><br>
</tbody>
</table>

PHP Adding elements with the array to database not working

I have array which get all E-mails which are invited by the user before. I checking which e-mails are selected by checkbox and then I add them to the table 'zaproszenia'. The array saves the records. When i click the button 'Zapisz'(SAVE) I have error:
Notice: Undefined offset: 1 in D:\xampp\xampp\htdocs\inzynierka\inzynierka\zaproszenia.php on line 91
This line is:
$tabMail=$mail_array[$i];
I want save to the table 'zaproszenia' the e-mail which is select by checkbox. I have no idea how do that. I was trying and trying and nothing.Sorry about my english. I hope that I describing the problem clear.
Code fragment with file: zaproszenia.php - List the emails and checkboxes for them:
<form method="post">
<table class="table table-striped">
<thead>
<tr>
<th>Email_goscia</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Kod_dostepu</th>
<th>Data ważności kwest.</th>
</tr>
</thead>
<tbody>
<?php
$sqlc=mysqli_connect('127.0.0.1','root','');
if($sqlc)
{
$sql_q="USE aplikacja";
mysqli_query($sqlc,$sql_q);
//wyświetlanie listy gości dodanych przez uzytkownika globalnie tzn. to jest lista z ktrej uzytkownik wybiera ktrych gosci chce zaprosić do konkretnego kwestionariusza
$sql_q=mysqli_query($sqlc, "SELECT * FROM goscie g, uzytkownicy_goscie ug WHERE g.Email_goscia=ug.Email_goscia AND ug.Login='$log' ");
$lp=1;
if(mysqli_num_rows($sql_q) != 0)
{
$licznik=0;
while ($recordG=mysqli_fetch_array($sql_q))
{
?><tr>
<td> <?php echo $mail = $recordG['Email_goscia'];
$mail_array=array($licznik => $mail);
$licznik++; //$_SESSION['tablicaMail']=$mail_array; print_r($_SESSION);
print_r($mail_array);
?></td>
<td> <?php echo $recordG['Imie'];?> </td>
<td> <?php echo $recordG['Nazwisko']; ?> </td>
<td> <?php echo $recordG['Kod_dostepu'];?></td>
<td> <?php echo '<input type="date" name="data_waznosci'.$lp.'" id="data_waznosci'.$lp.'">'; ?> </td>
<td> <?php echo '<td><input type="checkbox" name="zaznaczyc'.$lp.'" id="zaznaczyc'.$lp.'" class="ClassZaznacz" onchange = "zaznacz();"/> <br /></td>'; ?> </td>
</tr>
<?php
$lp++;
}
}
else
{
echo "Użytkownik nie dodał jeszcze żadnych gości";
} ?>
</tbody>
</table>
<input type="submit" class="btn btn-primary" name="zapros" id="zapros" value="Zapisz zmiany" />
</form>
Save the selected emails by checkboxes:
<?php
if (isset($_POST['zapros']))
{
$data_zaproszenia = date("Y-m-d");
$liczba = count(preg_grep('/^data_waznosci[\d]*/', array_keys($_POST)));
echo $liczba;
if(mysqli_num_rows($sql_q) != 0)
{
for ($i=1; $i <= $liczba ; $i++)
{
/*while ($recordG=mysqli_fetch_array($sql_q)) {
$mail = $recordG['Email_goscia'];
$mail_array=array($mail);
} print_r($mail_array); //$mail = $recordG['Email_goscia']; //echo $mail; */
if (isset($_POST["zaznaczyc".$i]))
{
$sql_wyniki = mysqli_query($sqlc, "INSERT INTO wyniki (Data_wypelnienia, ID_kwestionariusza) VALUES (NULL, $id)");
$id_wyniku=mysqli_query($sqlc, "SELECT ID_wyniku FROM wyniki WHERE ID_kwestionariusza=$id");
$id_wyniku2 = mysqli_fetch_assoc($id_wyniku);
$data_waznosci = $_POST['data_waznosci'.$i];
//$tablicaMail1 = $_SESSION['tablicaMail'][$i]; //print_r($_SESSION); // echo $tablicaMail1;
$tabMail=$mail_array[$i];
$sql_zaproszenie=mysqli_query($sqlc, "INSERT INTO zaproszenia (Email_goscia, ID_kwestionariusza, ID_wyniku, Data_zaproszenia, Data_waznosci, Wynik, Ocena, Status)
VALUES ('$tabMail', $id, '$id_wyniku2[ID_wyniku]', '$data_zaproszenia', '$data_waznosci', NULL, NULL, 'Status')"); //dodawanie kolejnych odpowiedzi do bazy
echo "<script type='text/javascript'>alert('Zaproszenie wysłano!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Zaproszenia NIE wysłano!');</script>";
}
}
}
mysqli_close($sqlc);
}
}
else
{
echo mysqli_connect_errno();
}
?>
Replace below Line. it was crating new array every time with assignment operator
$mail_array=array($licznik => $mail);
//change this line to
$mail_array[$licznik]=$mail;

how to search date field using php - mysqli

I'm having trouble searching the date field of mysql database.. I have a html form..that allows the user to choose 3 different ways to search the database.. field 1 is student_id, field 2 is lastname, field 3 is date. Well when i run the program and choose student id, I get the proper result back, when i do the same using last name I get the proper result back, but when i use date..I do not get any return. I happen to know what the result should be because i see it in the database..and besides that its the same data record as the student id, and last name. I think it might have something to do with format, but I can't figure it out..
I do not know aJax so please don't suggest ajax code right now.
here is the html code.
[code]
-- start javascript -->
<script type="text/javascript">
/*<![CDATA[ */
function check(){
if(document.lastname.last.value == "" || document.lastname.last.value == null)
{
alert("no last name entered");
return false;
}
}
function checkdate() {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}
}
function fieldSwap(image){
var sb = document.getElementById('sb');
if(sb.value == ""){
sb.style.background = "url(images/"+image+") no-repeat";
}
}
function buttonSwap(image){
var sb = document.getElementById('sb');
sb.src = "images/"+image;
}
function validate(){
var x = document.information.search.value;
if (x.length<10 || x.length>10){
alert("student id is incorrect");
return false;
}
}
/*]]> */
</script>
<!-- end javascript -->
</head>
<body>
<div id="form_wrap"><!-- start form wrap -->
<div id="form_header">
</div>
<div id="form_body">
<p>Search for a certification request (Enter one of the following):</p>
<form action="search.php" method="POST" name="information" id="information" onsubmit="return(validate()or return(checkdate())">
<div class="field">
<select name="type">
<option value="student_id">Student ID</option>
<option value="last_name">Last name</option>
<option value="examDate">Exam date</option>
</select>
<input name="typeValue" value="" />
<input type="submit" value="Search" />
</form>
</div>
</div>
</div><!-- end form wrap -->
</body>
</html>
<form action = "" method = "POST">
<div class="field">
<label for = "first_name"> first_name</label>
<input type = "text" name = "first_name" id = "first_name">
</div>
<div class = "field">
<label for = "last_name"> last_name </label>
<input type ="text" name = "last_name" id = "last_name">
</div>
<div class = "field">
<label for = "bio"> bio </label>
<textarea name = "bio" id = "bio"></textarea>
</div>
<input type = "submit" value = "Insert">
</form>
[/code]
Here is the PHP code
[code]
$records = array();
$typeValue = $_REQUEST['typeValue'];
//If they did not enter a search term we give them an error
if ($typeValue == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// We perform a bit of filtering
//$typevalue = strtoupper($search);
$typeValue = strip_tags($typeValue);
$typeValue = trim ($typeValue);
$value = $_POST['typeValue'];
if($_POST['type'] == "student_id")
{
//Query with $value on student_id
if($result = $db->query("SELECT * FROM records WHERE student_id LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "last_name")
{
//Query with $value on last_name
if($result = $db->query("SELECT * FROM records WHERE last_name LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "examDate")
{
//Query with $value on date
if($result = $db->query("SELECT * FROM records WHERE examDate LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
//$anymatches=$result;
//if ($anymatches == 0 )
//{
//echo "Sorry, but we can not find an entry to match your query...<br><br>";
//}
//And we remind them what they searched for
//echo "<b>Results For:</b> " .$typeValue;
//}
?>
<!DOCTYPE html>
<html>
<style type="text/css">
th{text-align: left;}
table, th, td{ border: 1px solid black;}
</style>
<head>
<title>Search Result</title>
</head>
<body>
<h3> Results for <?php echo $typeValue ?> </h3>
<?php
if(!count($records)) {
echo 'No records';
} else {
?>
<table style="width:100%">>
<th>
<tr>
<th>student_id</th>
<th>First name</th>
<th>Last name</th>
<th>email</th>
<th>Major</th>
<th>Exam Name</th>
<th>Taken class</th>
<th>Prepare</th>
<th>MeasureUp Key</th>
<th>Exam Date</th>
<th>Request Made On</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r){
?>
<tr>
<td><?php echo $r->student_id; ?></td>
<td><?php echo $r->first_name; ?></td>
<td><?php echo $r->last_name; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->major; ?></td>
<td><?php echo $r->examName?></td>
<td><?php echo $r->taken_class; ?></td>
<td><?php echo $r->prepare; ?></td>
<td><?php echo $r->measureUpKey; ?></td>
<td><?php echo $r->examDate; ?></td>
<td><?php echo $r->request_made; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</html>
<html>
<head></head>
<body>
<br/>
Return to Search
</body>
</html>
[/code]
I Believe you are using like to get the Exam Dates for that session or month so you can use this
Using DATE_FORMAT function
SELECT * FROM records WHERE DATE_FORMAT(examDate, '%Y %m') = DATE_FORMAT('$typeValue', '%Y %m') ORDER BY examDate
or may be you are looking for a specific date than
SELECT * FROM records WHERE examDate = '$typeValue'

I cannot get a repeating table with a repeating drop down to show answers previously selected from MySQL database in PHP

I have a table with the table headings below. Each row of that table populates info from a database. One of those columns (category) is a drop down menu (with a LOT of entries), so I've used a separate table to pull the values from. When a user submits the page with the drop down value selected, I want them to see the value they chose last time, as they may have to come back to this form multiple times. If you look at where the var_dump is, I can see that it's pulling the previously selected values from the database, but when I try to use the very same $row["category"] entry in the selected = $row["category"] I get the first entry in the drop down list, NOT the selected value (which was again verified as existing with the var_dump). I have no idea why this is happening and have spent DAYS trying to figure this out before asking the community here. Thanks for any help you can provide.
<body>
<table>
<tr>
<th scope="col">Date</th>
<th scope="col">Amount</a></th>
<th scope="col">Vendor</th>
<th scope="col">Description</th>
<th scope="col">Category</th>
<th scope="col">Notes</th>
<th scope="col">Bind Values?</th>
<th scope="col">Trip</th>
<th scope="col">Last Updated</th>
<th scope="col">Updated By</th>
<th scope="col">Done</th>
</tr>
<?php
$category_query = "SELECT * FROM category order by category_name ASC";
$category_result = mysqli_query($connection, $category_query);
$category_options = NULL;
while ($category = mysqli_fetch_assoc($category_result)) {
$category_options .= sprintf("<option value='%s'>%s</option>".PHP_EOL, $category["category_name"], $category["category_name"]);
}
?>
<form action="process_table.php" method="post">
<?php
$transactions_query = "SELECT transactions_id, `date`, amount, vendor, description, category , trip, last_updated, last_updated_by, done, notes\n"
. "FROM users, transactions\n"
. "WHERE users.user_name = '{$_SESSION["user"]}' AND users.users_id = transactions.users_id";
$transactions_result = mysqli_query($connection, $transactions_query);
while ($row = mysqli_fetch_assoc($transactions_result)) {
$id = $row["transactions_id"];
var_dump($row["category"]);
?>
<tr>
<td><?php echo date("F d, Y", strtotime($row["date"]));?></td>
<td><?php echo number_format($row["amount"], 2);?></td>
<td><?php echo $row["vendor"];?></td>
<td><?php echo $row["description"];?></td>
<td> <?php
if ($row["done"] == "checked") {
echo '<select selected ="'.$row["category"].'" name="expense['.$id.'][category]">'.$category_options.'</select>';
} else {
echo "DUMB"/*'<select name="expense['.$id.'][category]">'.$category_options.'</select>'*/;
}
?>
</td>
<td><?php echo "<textarea name='expense[" . $id . "][notes]'>" . $row["notes"] . "</textarea>";?></td>
<td><input name="bind" type="checkbox" value="YES"></td>
<td nowrap="nowrap">Trip place holder</td>
<td><?php echo date("m/d/Y")?></td>
<td>
<?php
if (!isset($_SESSION["user"])) {
echo "temp" ;
} else {
echo $_SESSION["user"];
}
?>
</td>
<td><?php echo "<input name='expense[" . $id . "][done]' type='checkbox'"?> <?php if($row["done"] == "checked") {
echo "checked = 'checked'>";
} else {
echo ">";
}
?>
</td>
</tr>
<?php
}
?>
</table>
<input name="submit" type="submit" id="submit" >
</form>
</body>
To show a option as selected, you need to apply the attribute selected="selected" to the <option> not the <select> element - The attribute as you currently have it will just be ignored, where most browsers will default to the first item in the list.
Change this:
<select selected ="'.$row["category"].'"
To this:
<select name="name">
<option value="option1">Value 1</option>
<option value="option2" selected="selected">Value 2</option>
</select>
In the above example the option2 option will be selected.
(edit) Using your own code:
<select name="<?php echo sprintf('expense[%s][%s]', $id, $category); ?>">
<option value="">Please select…</option>
<?php
foreach($category = mysqli_fetch_assoc($category_result)) :
if ($row["category"] == $category['category_name']) {
echo '<option value="'. $category['category_name'] .'" selected="selected">'. $category['category_name'] . "</option>";
} else {
echo '<option value="'. $category['category_name'] .'">'. $category['category_name'] . "</option>";
}
endforeach;
?>
</select>

Categories