set default value in option select dropdown which the user selected php - php

First let's assume that the user has selected an ID to edit the specific data.
Here's where the user select to edit
Output will be here
But my problem is that it's not highlighting the specific data where the user need to edit and if the user save it the value will be 0 or null.
Error1 Error2
I want to highlight the specific data where the user need to edit like this one..
Hihglighted
I have 2 queries:
Here's are all my query to get the subject , semester/term and schoolyear:
$sql1 = "select * from subject";
$subject = $conn -> query($sql1);
$sql2 = "select * from sy";
$sy = $conn -> query($sql2);
$sql3 ="select * from term";
$semester = $conn -> query($sql3);
and here's my query to get the subject code and the subject description where the user select the id to edit..
$sql4 = "select subject.Subject_Description ,subject.Subject_Code, subject_offer.Subject_Offer_ID, term.Term_Name
from subject_offer
inner join subject on subject_offer.Subject_Code = subject.Subject_Code
inner join term on subject_offer.Term_ID = term.Term_ID
where subject_offer.Subject_Offer_ID = '$id'";
$result = $conn -> query($sql4)->fetch_object();
Here's the code for my dropdown or option select..
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Subject</label>
<div class="col-sm-7">
<select class="form-control form-control-md col-sm-12" id="inputSmall" name="subject">
<option disabled selected ><?php echo $result->Subject_Code . '' .$result->Subject_Description ?></option>
<?php while($row1 = $subject->fetch_object() ): ?>
<option value="<?php echo $row1->Subject_Code ?>" >
<?php echo $row1->Subject_Code.' '.$row1->Subject_Description; ?>
</option>
<?php endwhile; ?>
</select>
</div>
</div>

There is no Term_ID in select clause of your second query. Also, you are missing value attribute in your disabled option. Should be:
<option disabled selected value="<?php echo $result->Subject_Code ?>">
<?php echo $result->Subject_Code . ' ' .$result->Subject_Description ?>
</option>
I usually do it differently, that is, mark the selected option when its value is the current one:
<select class="form-control form-control-md col-sm-12" id="inputSmall" name="subject">
<?php while($row1 = $subject->fetch_object() ): ?>
<option value="<?php echo $row1->Subject_Code ?>" <?= $row1->Subject_Code === $result->Subject_Code ? 'selected' : '' ?>>
<?php echo $row1->Subject_Code.' '.$row1->Subject_Description; ?>
</option>
<?php endwhile; ?>
</select>

Related

How to echo the selected value from an array fetched from the database

I want to echo the selected value from the database to update it then store it
for example I have an asset with category printers from table category which contains other categories and when I want to edit this asset on the edit page I should get a dropdown list contains all the categories and selected on printers then if I want to change it I will if not leave unchanged
The array is drop-down from table category inner joined with user_asset table in the database by asset_category as a foreign key
this is what I have done so far
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required>
<?php while( $row = mysqli_fetch_array($result)) {?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['cate_name'];?>
</option>
<?php }?>
</select>
</div>
You can add if check if ($row['cate_name'] == 'computer') { ?> and then add selected to this option:
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required >
<?php while( $row = mysqli_fetch_array($result)) {
if ($row['cate_name'] == 'computer') { ?>
<option value="<?php echo $row['category_id'];?>" selected><?php echo $row['cate_name'];?></option>
<?php } else { ?>
<option value="<?php echo $row['category_id'];?>"><?php echo $row['cate_name'];?></option>
<?php }
}?>
</select>
Notice: If you have multiple elements with that category it will select the last one.
the answer is very simple.. let's put this code
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required>
<?php while( $row = mysqli_fetch_array($result)) {
if($row['cate_name']== printers) { ?>
<option value="<?php echo $row['category_id'];?>" selected="selected">
<?php echo $row['cate_name'];?> </option>
<?php } else { ?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['cate_name'];?> </option>
<?php }?>
</select>
</div>
The logic is that using while loop, checking the condition using if class, and when it satisfies make it as selected. Then it will be echo as selected Value.

selected value get from db into Data list option using php mysql

I need to get selected value from db into datalist box.Tell me how to do it. Here is the code.
<input list="Rank_Name" class="form-control" required>
<datalist id="Rank_Name">
<?php
$sel_cus = "select Rank_Name from ranks where Rank_Status=1";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {
?>
<option value="<?php echo $row['Rank_Name'];?>"></option>
<?php
}
?>
</datalist>
If i understood right , you need to select value in dropdownlist with other value also. You can achieve this by doing this
<?php
$select1="select Rank_Name from ranks where Rank_Status=1";
$q=mysqli_query($select1) or die($select1);
$row=mysqli_fetch_array($q); //here you are getting name of person whose rank is 1
?>
<datalist id="Rank_Name">
<?php
$s="select * from ranks ";
$q=mysqli_query($s) or die($s);
while($r=mysqli_fetch_array($q))
{ ?>
<option value="<?php echo $r['Rank_Name']; ?>"<?php if($row['Rank_Name']==$r['Rank_Name']) echo 'selected="selected"'; ?>>
<?php echo $r['Rank_Name']; ?>
</option>
<?php } ?>
</datalist>
In above code, this line <?php if($row['Rank_Name']==$r['Rank_Name']) echo 'selected="selected"'; ?> check if value are same from first query ,and if same then that option will be get selected automatically
<input list="Rank_Name" class="form-control" required>
<datalist id="Rank_Name">
<?php
$sel_cus = "select Rank_Name from ranks where Rank_Status=1";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {
echo "<option value=".$row['Rank_Name']."></option>";
}
?>
</datalist>
try this code.
im using echo <option> with while loop

Generating reports based on user input in php

I have a form to generate reports. In my form only the from_date and to_date fields are mandatory. If the user selects only from_date and to_date then I need to generate all the sales between those dates. If he/she wants to generate cash & credit wise or party wise or agent wise reports (these fields are on the right side of the form), then I should be able to generate reports customized that way also. I'm not able to write the logic to create the SQL query. Thank You!
HTML:
<form class="row" id="reports" style="width: 100%; margin-bottom: 1%">
<div class="pull-left clearfix">
<label for="from" class="lab-sm">From:</label>
<input type="date" id="from" name="from" value="<?php echo date("2016-09-20"); ?>">
<label for="to" class="lab-sm">To:</label>
<input type="date" id="to" name="to" value="<?php echo date("Y-m-d"); ?>">
<div>
<label for="to" class="lab-sm">Inv:</label>
<select name="purchase" id="purchase" class="inp-sm">
<option value="INV">All</option>
</select>
</div>
</div>
<div class="pull-right clear-left" style="position: relative;">
<div>
<select name="payment" id="payment" class="inp-lg">
<option value="">Cash & Credit Sales</option>
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
</select>
</div>
<div>
<select name="party" id="party" class="inp-lg">
<option value="">-- All Parties --</option>
<? $query = $con->query("SELECT la_head FROM ledger_accounts"); ?>
<? while($row = mysqli_fetch_array($query)) { ?>
<option value="<?php echo $row['la_head']; ?>"><? echo $row['la_head']; ?></option>
<? } ?>
</select>
</div>
<div>
<select name="agent" id="agent" class="inp-lg">
<option value="">-- All Agents --</option>
<? $query = $con->query("SELECT la_agent FROM ledger_accounts"); ?>
<? while($row = mysqli_fetch_array($query)) { ?>
<option value="<?php echo $row['la_agent']; ?>"><? echo $row['la_agent']; ?></option>
<? } ?>
</select>
</div>
<!-- submission -->
<div style="position: relative; left: 44px">
<input type="submit" value="Generate">
<input type="hidden" name="reports" value="sales_reports">
</div>
</div>
</form>
PHP:
if (ISSET($_POST['reports']) && $_POST['reports'] === 'sales_reports') {
$from_date = $con->real_escape_string($_POST['from']);
$to_date = $con->real_escape_string($_POST['to']);
$payment_type = $con->real_escape_string($_POST['payment']);
$party = $con->real_escape_string($_POST['party']);
$agent = $con->real_escape_string($_POST['agent']);
$query = "SELECT *
FROM sales
INNER JOIN ledger_accounts ON sales.la_id = ledger_accounts.la_id
INNER JOIN inventory_items ON sales.item_no = inventory_items.item_no
WHERE inv_date >= ? AND inv_date <= ?
AND sales.payment_type = COALESCE(?, sales.payment_type)
AND ledger_accounts.la_head = COALESCE(?, ledger_accounts.la_head)
AND ledger_accounts.la_agent = COALESCE(?, ledger_accounts.la_agent)";
$stmt = $con->prepare($query);
$stmt->bind_param('sssss', $from_date, $to_date, $payment_type, $party, $agent);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>'.$row['inv_date'].'</td>';
echo '<td>'.$row['inv_no'].'</td>';
echo '<td>'.$row['la_head'].'</td>';
echo '<td>'.$row['la_address'].'</td>';
echo '</tr>';
}
If you are expecting that you may not get a value for all parameters, you can do the following using COALESCE():
$query = "SELECT *
FROM sales
INNER JOIN party ON sales.party_id = party.party_id
INNER JOIN items ON sales.item_no = items.item_no
WHERE inv_date >= ? AND inv_date <= ?
AND payment_type = COALESCE(?,payment_type)
AND party = COALESCE(?,party)
AND agent = COALESCE(?,agent);";
$statement = $dbConn->prepare($query);
$statement->bind_param('sssss',$from_date,$to_date,$payment_type,$party,$agent);
COALESCE() works by providing the first non-null value. So, if the parameter passed in is NULL, then the above will just match whatever is in the field you are filtering on (party = party).
You want to parameterize you query, too, as to avoid potential SQL-injection attacks. I have applied that to the code above as well.
Good resources:
http://php.net/manual/en/mysqli-stmt.bind-param.php
How can I prevent SQL injection in PHP?

Save ID from dropdown list into other table

I have a form with fields and one dropdown list. The data from the dropdown list comes out the table: categorie. (fields are: catID, catName)
When I select a categorie from the drop down list and fill all the other input fields, it saves all the input fields and only the catName from the categorie table into the tabel: event.
How can I also save the selected catID from the categorie table into the event table?
Can someone helm me out here?
Regards, Benny
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catID = $_POST["catID"];
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$eventName}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID}')");
header('Location: eventOK.php');
}
?>
<form action="" method="post" name="RegisterForm" id="RegisterForm">
<div class="FormElement">
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option id="<?php echo $ViewAllCategories['catID']; ?>"><?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
</select>
You made a mistake in <option id="id"></option>
if you wanna take value from select child.
you must change id to value="" or you must add value="id" proper.
change your select box block completely like below..
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?PHP echo $ViewAllCategories['catID'].'-'.$ViewAllCategories['catName']; ?>"> <?PHP echo $ViewAllCategories['catName']; ?></option>
<?php } ?>
</select>
and a tip for mysql query... to the best of one's ability don't use "select * from" use it if you dont need to all colums better than "*"
$con->query("SELECT catID, catName FROM categorie");
PHP file
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
//$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catIDs = $_POST["SelCatName"];
$catID = explode("-", $catIDs);
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$catID[1]}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID[0]}')");
header('Location: eventOK.php');
}
?>
to me you are missusing the attribute of ID, Replace the ID for value: your option tag already have the id and name
<select name="SelCatName" class="TField" id="SelCatName">
your code will be:
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?php echo $ViewAllCategories['catID']; ?>"> <?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
Therefore you will find your post as only SelCatName = (numerical ID)
Now, if you need that the list of the catID and catName stores to the next page you can re-run your query in the next page and store them in an array.

listbox value goes 0 in database if not selected on edit mode in php

I have three tables
City: city_id, city_name
State: State_id, State_name
News: City_id, State_id, Headline, Story, Author etc.
I am Displaying data in textbox and listbox on edit button click Of Selected ID.
Data is displaying in listbox properly of selected id but when i click save button without change of listbox value it goes 0 in database.
If I don't change the listbox value and click save then it inserting 0 from listbox.
<?php
$data = 0;
if(isset($_GET['edit']))
{
$id = clean($_GET['edit']);
mysql_set_charset('utf8');
$sql="SELECT city_name,state_name,category_name,headline,author,story,source,photo,date from news left join
city on news.city_id=city.city_id left join state on news.state_id=state.state_id left join category on news.cat_id=category.category_id where id = '$id'";
$result=mysql_query($sql);
$data=mysql_fetch_array($result);
}
?>
<?php
$cat = $Admin->select($Admin->cat_table,'','','');
?>
<select name="cat_id" class="select" required="">
<option value="<?php if(isset($_GET['edit'])){ echo $data['category_name']; }?>"><?php if(isset($_GET['edit'])){echo $data['category_name'];}?></option>
<?php
foreach($cat as $load_category)
{
?>
<option value="<?php echo $load_category["category_id"]; ?>"><?php echo $load_category["category_name"]; ?></option>
<?php }?>
</select>
<?php
$errors = array();
$Admin = new admins;
if(isset($_POST['save']))
{
$table = $Admin->news_table;
if(isset ($_GET['edit']))
{
$id = clean($_GET['edit']);
$cond = "id = '$id'";
if($Admin->save_advance($table,$_POST,'',$cond))
{
$_SESSION['message'] = "News Updated Successfully";
header("Location:add_news.php");
exit;
}
}
}
?>
What am I doing wrong?
Tell me if I'm wrong but this line
<option value="<?php if(isset($_GET['edit'])){ echo $data['category_name']; }?>">
<?php if(isset($_GET['edit'])){echo $data['category_name'];}?>
</option>
seems strange to me, it sets the category name as value for first option in the select. Basically, if you don't change the listbox, you are trying to update a row where the category_id is a category_name.
This should be:
<option value="0">
<?php if(isset($_GET['edit'])){echo $data['category_name'];}?>
</option>
But if you have to update something you can't do that without a value. So add some kind of validation that forbids to click the save button without setting a value in the select, or just do something like this (adds a default category to the listbox)
<select name="cat_id" class="select" required>
<?php
$counter = 0;
foreach($cat as $load_category){ ?>
<option <?php echo ($counter == 0) ? 'selected' : ''; ?> value="<?php echo $load_category["category_id"]; ?>"><?php echo $load_category["category_name"]; ?></option>
<?php
//increments counter
$counter++; }?>
</select>

Categories