I have a drop down that is enabled by default and shows options populated from the database. When an option is selected that is now blank it enables the drop down to the side if it.
echo '
<script>
function check(){
if(document.getElementById("company").value!="")
document.getElementById("stores").disabled=false;
else
document.getElementById("stores").disabled=true;
}
</script>
<label class="form-control-label" for="input-last-name">Company</label>
<select type="text" id="company" name="company" class="form-control form-control-alternative" onchange="check()">
<option></option>';
$sql = "SELECT * FROM companies WHERE CompanyID != '4'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['CompanyID'].'>'.$row['CompanyName'].'</option>';
}
}
echo'
</select>
<label class="form-control-label" for="input-last-name">Store </label>
<select id="stores" name="stores" class="form-control form-control-alternative" disabled>
<option></option>';
$sql = "SELECT * FROM stores";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['storeid'].'>'.$row['storename'].'</option>';
}
}
echo '
</select>';
As you can see selecting an item from the companies dropdown enables the stores dropdown to be enabled. However at the moment it shows all stores - not stores assigned to that company the SQL needs to be
SELECT * FROM store WHERE StoreID = $SelectedCompanyID
and not
SELECT * FROM store
I cannot work out a way to populate a variable to complete the query and reload the drop down correctly with correct stores without reloading the page and loosing the rest of the inputs already completed in the form.
Any help would be appreciated.
Created a new page called fetch_data.php with the following code below
<?php
if(isset($_POST['get_option']))
{
include('includes/config.php');
$companies = $_POST['get_option'];
$sql = "SELECT * FROM stores WHERE companyid = '$companies'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['storeid'].'>'.$row['storename'].'</option>';
}
}
exit;
}
?>
Changed my HTML / PHP to look like this
echo '
<script>
function check(){
if(document.getElementById("company").value!="")
document.getElementById("stores").disabled=false;
else
document.getElementById("stores").disabled=true;
}
</script>
<label class="form-control-label" for="input-last-name">Company</label>
<select type="text" id="company" name="company" class="form-control form-control-alternative" onchange="check()">
<option></option>';
$sql = "SELECT * FROM companies WHERE CompanyID != '4'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['CompanyID'].'>'.$row['CompanyName'].'</option>';
}
}
echo'
</select>
<label class="form-control-label" for="input-last-name">Store </label>
<select id="stores" name="stores" class="form-control form-control-alternative">
</select>';
Then finally implemented in the JavaScript to do it.
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: "post",
url: "fetch_data.php",
data: {
get_option:val
},
success: function (response) {
document.getElementById("stores").innerHTML=response;
}
});
}
</script>
Related
I have a table that displays the records stored in a database. I have customized my pagination differently from what bootstrap uses to look like phpMyAdmin table pagination. What I have done so far works perfectly but refreshes the page on each user selection. I am stuck on how to use ajax to make the pagination work fine without refreshing the page.
Here's the HTML code to display the table with checkbox, select input and pagination links
<!--DISPLAY TABLE-->
<form class="" name="frmDisplay" id="frmDisplay" method="POST" action="">
<div id="display_table"></div>
<input type="checkbox" name="check" id="check" onchange=""></input> <label for="check">Show All</label>
<label class="clabel">|</label>
<label class="clabel" for="rowno">Number of Rows:</label>
<select class="" id="rowno" name="rowno" style="width:50px;height:25px;margin-bottom:3px;">
<option value='all' hidden disabled>All</option>
<?php
//set the value of $rowno
$rowno = isset($_POST['rowno'])?$_POST['rowno']:5;
if($rowno == 5)
{
$rowno = isset($_GET['limit'])?$_GET['limit']:5;
}
?>
<option value='5' <?=$rowno==5?'selected':''?>>5</option>
<option value='10' <?=$rowno==10?'selected':''?>>10</option>
<option value='15' <?=$rowno==15?'selected':''?>>15</option>
<option value='20' <?=$rowno==20?'selected':''?>>20</option>
<option value='25' <?=$rowno==25?'selected':''?>>25</option>
<option value='30' <?=$rowno==30?'selected':''?>>30</option>
</select>
<label class="clabel">|</label>
<label class="clabel" for="filter">Filter Rows:</label>
<input class="" style="width:50%;height:25px;margin-bottom:10px;" id="filter" name="filter" placeholder="Filter this table" onkeyup="filtertbl();"></input>
<div class='table-responsive-sm' style='width:100%;margin-top:10px;'>
<?php
//code to fetch all records from database on checkbox checked
if(isset($_POST['check']))
{
$sql = "SELECT *FROM evatbl WHERE RegNo = ?";
if($stmt = $con->prepare($sql))
{
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows>0)
{
$count = 1;
echo "<table id='t01'' class='table'>
<tr id='tblhead'>
<th>SN</th>
<th>Course Title</th>
<th>Course Code</th>
<th>Credit Unit</th>
<th>Course Lecturer</th>
<th>Rating(%)</th>
</tr>";
while($row = $result->fetch_assoc())
{
$ccode = $row['CourseCode'];
$ctitle = $row['CourseTitle'];
$cunit = $row['CreditUnit'];
$clec = $row['CourseLecturer'];
$crate = $row['Rating'];
echo "
<tr>
<td>$count</td>
<td>$ctitle</td>
<td>$ccode</td>
<td>$cunit</td>
<td>$clec</td>
<td>$crate</td>
</tr>";
$count++;
}
}
else{
echo "<p style='color:darkblue;margin-bottom:0;'>Oops! No records found.</p>";
}
}
}
else
{
//code for pagination
//get current page
$currentpage = isset($_GET['currentpage']) ? $_GET['currentpage'] : 1;
$no_of_records_per_page = $rowno;
$setoff = ($currentpage - 1) * $no_of_records_per_page;
//get total number of records in database
$sqlcount = "SELECT *FROM evatbl WHERE RegNo = ?";
$stmt = $con->prepare($sqlcount);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
$totalpages = ceil($num_rows/$no_of_records_per_page);
//query for pagination
$sqllimit = "SELECT *FROM evatbl WHERE RegNo = ? ORDER BY CourseTitle LIMIT $setoff, $no_of_records_per_page";
if ($stmt = $con->prepare($sqllimit))
{
$stmt = $con->prepare($sqllimit);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if ($num_rows>0)
{
$count = 1;
echo "<table id='t01' class='table' width='100%'>
<tr id='tblhead'>
<th>SN</th>
<th>Course Title</th>
<th>Course Code</th>
<th>Credit Unit</th>
<th>Course Lecturer</th>
<th>Rating(%)</th>
</tr>";
while($row = $result->fetch_assoc())
{
$ccode = $row['CourseCode'];
$ctitle = $row['CourseTitle'];
$cunit = $row['CreditUnit'];
$clec = $row['CourseLecturer'];
$crate = $row['Rating'];
echo "
<tr>
<td>$count</td>
<td>$ctitle</td>
<td>$ccode</td>
<td>$cunit</td>
<td>$clec</td>
<td>$crate</td>
</tr>";
$count++;
}
}
else{
echo "<p style='color:darkblue;margin-bottom:0;'>Oops! No records found.</p>";
}
echo "</table>";
?><br>
<div class="nav_div">
<?php
//First Page Button
if($currentpage > 1)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."¤tpage=".(1)."' title='First'><<</a>";
}
//Previous Page Button
if($currentpage >= 2)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage - 1)."' title='Previous'><</a>";
}
?>
<select class='navno' name='navno' id='navno' onchange="pageNav(this)">
<?php
//Link to available number of pages with select drop-down
for($i = 1; $i <= $totalpages; $i++)
{
echo "<option class='bold'";
if ($currentpage==$i)
{
echo "selected";
}
echo " value='view_eva.php?limit=".$rowno."¤tpage=".$i."'>".$i."</option>";
}
?>
</select>
<?php
//Next Page Button
if($currentpage < $totalpages)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage + 1)."' title='Next'>></a>";
}
//Last Page Button
if($currentpage <= $totalpages - 1)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."¤tpage=".($currentpage = $totalpages)."' title='Last'>>></a>";
}
?>
</div>
<?php
}
}
?>
</form>
</div>
</div>
Here's the javascript that controls form submission on each user selection. I know this is where I'll need to use ajax requests but I can't figure out how. I've been on this for some days now.
<script type="text/javascript">
<?php
/*Using PHP to create a javascript variable that can be used to
add the `selected` attribute to the respective option*/
printf("let rownum='%s'", empty($_POST['rowno']) ? 0 : $_POST['rowno']);
?>
let myForm=document.forms.frmDisplay;
let mySelect=myForm.rowno;
let myCheck=myForm.check;
let myNavSelect=myForm.nav_no;
// find all options and if the POSTed value matches - add the selected attribute
// establish initial display conditions following page load / form submission
if(rownum)
{
if(rownum=='all') myCheck.checked=true;
Array.from(mySelect.querySelectorAll('option')).some(option=>
{
if(rownum==Number(option.value) || rownum=='all')
{
option.selected=true;
return true;
}
});
}
// listen for changes on the checkbox
myCheck.addEventListener('click',function(e)
{
if(myCheck.checked)
{
var msg = confirm('Do you really want to see all of the \nrows? For a big table this could crash \nthe browser.');
if(!msg)
{
myCheck.checked=false;
return false;
}
}
if(mySelect.firstElementChild.value=='all')
{
mySelect.firstElementChild.selected=this.checked;
mySelect.firstElementChild.disabled=!this.checked;
}
myForm.submit();
});
// listen for changes on the select
mySelect.addEventListener('change',function(e)
{
if(myCheck.checked) myCheck.checked=false;
myForm.submit();
});
//load url on the navigate select
function pageNav(option)
{
location.href = option.value;
}
</script>
Please, I need all the help I can get to complete this project. Thank you.
I am using below admin pannel:
https://github.com/harsh4870/phpcoreadmin
I have below code in the form (\forms\customer_form.php) where I can see static array ( <?php $opt_arr = array("India", "Middle East", "Nepal", "South Indian"); ?>), I would like to replace this static array to be picked from the MySql database (Table name: CUSTOMER| Column_name: STATE).
Thanks in advance
<div class="form-group">
<label>State</label>
<?php $opt_arr = array("Maharashtra", "Kerala", "Madhya pradesh"); ?>
<select name="state" class="form-control selectpicker" required>
<option value=" ">Please select your state</option>
<?php
foreach ($opt_arr as $opt) {
if ($edit && $opt == $customer['state']) {
$sel = 'selected';
} else {
$sel = '';
}
echo '<option value="'.$opt.'"' . $sel . '>' . $opt . '</option>';
}
?>
</select>
</div>
You'll need to start a MySQL connection and then submit a query.
Here's a quote from W3Schools.
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
Below is an example.
<?php
// Connection Info
$host = "localhost";
$user = "myuser";
$pass = "mypass";
$db = "mydb";
// Start Connection
$link = new mysqli($host, $user, $pass, $db);
// Check Connection
if ($link->connect_error) {
// Error Handler
die("MySQL Connection Error: ".$link->connect_error);
}
// Prepare Query
$query = "SELECT 'AREA_NAME' FROM 'REIGONAL_AREA'";
// Submit Query
$result = $link->query($query);
// Check for Errors
if ($result) {
// Set counter
$i = 0;
// Set data variable
$opt_arr = [];
// Loop through data
while($current = $result->fetch_assoc()) {
$output[$i] = $current[0];
$i++;
}
?>
<!DOCUMENT html>
<html>
<head>
<!-- Header Elements Go Here -->
</head>
<body>
<div class="form-group">
<label>State</label>
<?php $opt_arr = array("Maharashtra", "Kerala", "Madhya pradesh"); ?>
<select name="state" class="form-control selectpicker" required>
<option value=" ">Please select your state</option>
<?php
foreach ($opt_arr as $opt) {
if ($edit && $opt == $customer['state']) {
$sel = 'selected';
} else {
$sel = '';
}
echo '<option value="'.$opt.'"' . $sel . '>' . $opt . '</option>';
}
?>
</select>
</div>
</body>
</html>
<?php
} else {
// Error Handler
die("MySQL Error: ".$link->error);
}
?>
I want to have the datalist from "Serienummer" change based on what "Product" is chosen.
<td>Product</td>
<td>
<Select name="ProductID" placeholder="Productnaam" required>
<?php
$query2 = "SELECT DISTINCT ProductID FROM HW_Serial WHERE Prefix = '$prefix'";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$DisProductID=$row["ProductID"];
$query3 = "SELECT ProductID, ProductName FROM Products WHERE ProductID = '$DisProductID' order by ProductName";
$result3 = mssql_query($query3);
$numRows = mssql_num_rows($result3);
while($row = mssql_fetch_array($result3))
{
$xProductID=$row["ProductID"];
$xProductName=$row["ProductName"];
if ($ProductID == $xProductID) {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
} else {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
}
}
}
?>
</select>
</tr>
<tr>
<td>Serienummer</td>
<td>
<input list="devicesn" name="devicesn" autocomplete="off" placeholder="Serienummer" required>
<datalist id="devicesn">
<?php
$query2 = "SELECT devicesn FROM HW_Serial WHERE ProductID = '$ProductID' order by devicesn";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$xdevicesn=$row["devicesn"];
if ($devicesn == $xdevicesn) {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
} else {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
}
}
?>
My guess is that this has to be done by use of JavaScript but I'm a complete beginner when it comes to that.
Thanks in advance
You can redirect to current page with parameter when <select> changed. And receive the parameter in your php code in datalist section.
For example:
<select name="ProductID" placeholder="Productnaam" required onchange="location.href='?product' + this.value">...</select>
Then I just say sorry, I do not know how to receive url parameters like yourpage?p=project in PHP.
Ok, so I've checked the net and the other questions on here and I'm stumped. I've tried a javascript solution from a question posted on here but I think it's not liking MySQL populating the <option>s. I'll copy all the code I've got including the javascript I have.
SCRIPT:
<script>
$(function() {
$('#groups').on('change', function() {
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function() {
if (
$(this).attr('data-group') === val || $(this).attr('data-group') === 'SHOW'
) {
$(this).show();
} else {
$(this).hide();
}
});
});
$('#groups').trigger('change');
});
</script>
PHP 1st dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
PHP 2nd dropdown
<select class="form-control" id="sub_groups">
<option data-group='SHOW' value="0">Model</option>
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option data-group='".$row['BoilerBrand']."' value='".$row['BoilerGC']."'>".$row['BoilerModel']."</option>";
}
?>
</select>
Any help with this would be greatly appreciated!
Thanks :)
The way I normally do this is instead of hiding/showing the options I remove/add them. I believe if you hide the options then the select input can still have that value.
SCRIPT:
<script>
$(function(){
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
$models = array();
while ($row = mysql_fetch_array($result)) {
$models[$row['BoilerBrand']][] = $row;
}
/* should look like
$models = [];
$models[1][] = ['ModelID'=>'1','BoilerBrand'=>'1','BoilerModel'=>'240E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
$models[1][] = ['ModelID'=>'3','BoilerBrand'=>'1','BoilerModel'=>'290D','BoilerGC'=>'11-111-11','BoilerImage'=>'11-111-11.jpg' ];
$models[2][]= ['ModelID'=>'2','BoilerBrand'=>'2','BoilerModel'=>'250E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
*/
?>
var _boilermodels = '<?php echo json_encode($models); ?>';
var jsonBoilerModels = JSON.parse(_boilermodels);
console.log(jsonBoilerModels);
$('#groups').on('change', function(){
var $this = $(this);
var val = $this.val();
var sub = $('#sub_groups');
sub.find('option').remove();
var appendList = [];
$.each(jsonBoilerModels[val],function(key,value){
appendList.push('<option value="'.concat(value['BoilerGC'], '">', value['BoilerModel'], '</option>'));
});
sub.append(appendList);
});
$('#groups').trigger('change');
});
</script>
1st Dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT ID ,BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
2nd Dropdown:
<select class="form-control" id="sub_groups">
<option value="">Select A Model</option>
</select>
What Im trying to do is put one name into a input type box and press submit, once submitted Id like it only to show all the same name rows and NOT all names in database? Can anyone help as I'm trying out or || in the PHP but only getting all results?
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<button onclick="refreshMap()">Refresh</button>
</form>
function refreshMap() {
var name = $('#name').val();
}
<script>
$(function() {
$('#name').val(name);
});
</script>
PHP:
$query = "SELECT * FROM register WHERE name IN ('John' || 'Gina')";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
if(!empty($_POST['name']))
{
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}
EDIT:
$name = htmlspecialchars($_POST['name']);
if(!empty($name))
{
$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
exit(0);
}
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}