I have a database with course IDs and their corresponding course names. I'm trying to create a filter using a dropdown menu that filters the displayed courses.
Here's the code -
<body>
<div id="wrapper">
<?php // sqltest.php
include 'header.php';
include 'nav.php';
require_once 'login.php';
$conn = mysqli_connect($hn, $un, $pw, $db);
if (!$conn) {
die ('Fail to connect to MySQL: ' . mysqli_connect_error());
}
echo '<form action="" method="post">
<select name="Course Name">
<option value="All" selected="selected">All course names</option>
<option value="Introduction to Data Science">Introduction to Data Science</option>
<option value="Database Management Systems">Database Management Systems</option>
<option value="Data Visualization">Data Visualization</option>
</select>
<input type="submit" value="Search" name="submit" />
</form>';
$cname = isset($_POST['Course Name']) ? $_POST['Course Name'] : 'All';
if(isset($_POST)) {
if ($cname == 'Introduction to Data Science') {
$query = "SELECT * FROM courses WHERE Cname='Introduction to Data'";
} elseif ($cname == 'Database Management Systems') {
$query = "SELECT * FROM courses WHERE Cname='Database Management'";
} elseif ($cname == 'Data Visualization') {
$query = "SELECT * FROM courses WHERE Cname='Data Visualization'";
} elseif ($cname == 'All') {
$query = "SELECT * FROM courses";
}
$result = mysqli_query($conn, $query);
if (!$result) {
echo 'Could not get data: ' . mysqli_error($conn);
}
echo '<br>Available courses for hardcoded student 000-01-0002<br><br>';
echo '<table>
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th>Add</th>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>
<td>' . $row['cid'] . '</td>
<td>' . $row['Cname'] . '</td>
<td>Add</td>
</tr>';
}
}
echo '
</tbody>
</table>
</body>';
It displays all the courses when the page first loads but picking any one of the courses and clicking on submit does not change the initial table at all.
Remove the space in Course Name post field. It's not recognized as a valid POST field in your isset check because of the space.
Make it name="course_name" or something on select field.
Related
**Hello..i know my type of question has been answered in different questions before;but i tried them all..none worked!So please have a look on my issue.
I've a table that contains form input fields where values come from database.I didn't wanted the values to be edited.So used "readonly". But the problem is:By the inspect element of a browser when readonly is removed..then the value can be edited and blank input can be submitted !!! So i want to disable the editing or at least want to disable the submit button if input field is empty.**
The code of the table:
<?php
if (isset($_POST['show'])) {
$class = $_POST["Class"];
$sql = "SELECT * FROM students WHERE Class='$class' ORDER BY Roll ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
?>
<form action="" method="POST">
<table class="table table-bordered table-hover" style="width: 85%;text-align: center">
<tr >
<th>Roll</th>
<th>Student's Name</th>
<th>Attendance</th>
</tr>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><input value="<?php echo $row['Roll']; ?>" name="Roll[]" readonly required=""/></td>
<td><input value="<?php echo $row['Name']; ?>" name="Name[]" readonly required=""/></td>
<td><select name="Status[]">
<option value="0">0</option>
<option value="1">1</option>
</select></td>
</tr>
<?php } ?>
</table>
<input type="submit" name="save" value="Save" style="width: 50%;margin-left: 20%">
</form>
<?php
} else {
$message = "Sorry! No result!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$conn->close();
}
?>
The insertion code:
<?PHP
if (isset($_POST["save"])) {
foreach ($_POST["Roll"] as $rec => $value) {
$Roll = $_POST["Roll"][$rec];
$Name = $_POST["Name"][$rec];
$Status = $_POST["Status"][$rec];
$Date = date('Y-m-d');
$sql = "INSERT INTO `attendance`(`id`, `Date`, `Roll`, `Name`, `Status`) VALUES ('','$Date','$Roll','$Name','$Status')";
}
if ($conn->query($sql) === TRUE) {
$message = "Saved !";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
this is correct way to not input empty field
$class = $_POST["Class"];
if(!empty($class)) {
$sql = "SELECT * FROM students WHERE Class='$class' ORDER BY DESC or ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
}
}
?>
I edited part of your code to disallow editing. I hope it serves your pourpose. i used disabled attribute on the input tags.
<tr>
<td><input value="<?php echo $row['Roll']; ?>" name="Roll[]" disabled/></td>
<td><input value="<?php echo $row['Name']; ?>" name="Name[]" disabled/></td>
<td><select name="Status[]">
<option value="0">0</option>
<option value="1">1</option>
</select></td>
</tr>
subjects
course
chapters
I want to add 2 dynamic dropdown lists, one is for subjects, and one is for course. When I select subject, courses which is added to that subject should be loaded in the course dropdown list, and then add chapters to that courses.
How do I do that?
Any help would be appreciated.
Here is my code:
<div class="content-form-inner">
<div id="page-heading">Enter the details</div>
<div class="form_loader" id="thisFormLoader"></div>
<div id="error_message"></div>
<form name="thisForm" id="thisForm" action="editchapters.php?mode=<?php echo $_REQUEST['mode']; ?>&id=<?php echo $id; ?>" method="post" enctype="multipart/form-data">
<table border="0" cellpadding="0" cellspacing="0" id="id-form" >
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Subject</th>
<td style="width: 0%">
<select name="subject_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_subject ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($subject == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->subject_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->subject_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="subject_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Course</th>
<td style="width: 0%">
<select name="course_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_course ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($course == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->course_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->course_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="course_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th><span class="required">*</span>Chapter</th>
<td><input type="text" name="chapter_name" class="inp-form required" value="<?php echo $chapter;?>" style="color:#000 !important;"></td>
<td>
<div></div>
</td>
</tr>
<tr>
<th> </th>
<td valign="top"><input type="submit" name="submit_button" value="<?php echo $mode=="edit"? "Update" : "Add" ?>" class="form-submit" />
<input type="reset" value="Reset" class="form-reset" />
</tr>
</table>
</form>
<div class="clear"></div>
</div>
One possible solution would, if your data set is comparatively small. Load all the data on page load, and use jquery to get value of dropdown, and based on that formulate the values for the other drop downs.
Second Solution would be to us AJAX and call data from your database for every action. and print using Angular.
I've attached a sample code for that.
This is my_script.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$(document).ready(function(){
callSetTimeout();
});
function callSetTimeout(){
setTimeout(function(){
update();
callSetTimeout();
},200);
}
function update(){
$http.get("http://localhost/WhatsOnYourMInd/db.php")
.success(function (response) {$scope.names = response.records;});
}
});
This is for db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
$jsonString=array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($jsonString,array('id' =>$row['id'],'name' =>$row['name'],'message' =>$row['message']));
}
echo json_encode(array("records"=>$jsonString));
} else {
echo "0 results";
}
$conn->close();
?>
This is for index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Whats on your Mind</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<ul id="ajax"></ul>
<div ng-app="myApp" ng-controller="customersCtrl">
<ol>
<li ng-repeat="x in names">
{{ 'Id:'+x.id + ' Name:' + x.name +' Message:'+x.message}}
</li>
</ol>
</div>
<script src="my_script.js"></script>
</body>
</html>
Easiest way of creating dynamic dropdown is by using jquery inside the head tag.
Give onchange() event and guide the data to another page using jquery code, and then link 2 dropdowns. The code I did is like this, which I felt is the easiest way for dynamic dropdowns.
jquery which I included is
<script>
function ajaxDrp(data){
$.ajax({
method: "POST",
url: "chapterDropdown.php",
data: {
id: data
}
}).success(function(data) {
$('#selectCourse').empty();
$('#selectCourse').append(data);
});
}
</script>
#selectCourse is the id I have given to the other dropdown which have to be in sync with the first dropdown.
The given url in the jquery is the path where data of first dropdown is getting collected. In my case, the code is like this:
<?php
$id = $_REQUEST['id'];
$query = "SELECT * FROM `your table name` WHERE subject_id = " . $id;
$result = mysqli_query($dbhandle,$query);
$count = 0;
$option`enter code here` = '';
while($row = mysqli_fetch_assoc($result)) {
$option .= '<option
value="'.$row['id'].'">'.$row['course_name'].'</option>';
}
echo $option;
?>
I have been trying to pull the data from database mysqli in the drop down menu. Here is my code for postad.html. I want to pull categories data from categories table with a row name CatName. I also have CatId that shows ctegory id. Thank you in advance.Please help:
<html>
<head>
<title>Post AD</title>
</head>
<body>
<form method="POST" action="postad.php">
<table>
<tr>
<td>AdName:</td>
<td><input type="text" name="adname"></td>
</tr>
<tr>
<td>AdCategory</td>
<td>
//dropdown list
<select name="Categories">
<?php include = connect.php
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='". $row['CatName']."'>."</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="text" name="contactnumber"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="text" name="image"></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="description"></td>
</tr>
<tr>
<td>Expiration Date</td>
<td><input type="text" name="expirationdate"></td>
</tr>
<tr>
<td id="btn"><input type="submit" value='submit' name="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Looks like you have an error with your menu code. Should be this
echo "<option value=". $row['CatName'] ."></option>';
Opposed to
echo "<option value='". $row['CatName']."'>."</option>';
The result from the table is going to be a string regardless so there is no need to worry about value=''. The real problem was how you muffled up your quotes.
EDIT: Just noticed include = connect.php should be include 'connect.php';
<?php
$mysql_host = '';
$mysql_user = '';
$mysql_pass = '';
$mysql_dbase = '';
$mysql_table = '';
$pdo = new PDO('mysql:host=' . $mysql_host . ';dbname=' . $mysql_dbase, $mysql_user, $mysql_pass);
$sth = $pdo->prepare('SELECT * FROM `' . $mysql_table . '` ORDER BY `id` CatName');
$sth->execute();
$result = $sth->fetchAll();
foreach ($result as $row) {?>
<option value=<?php echo $row['CatName']; ?>></option>;
<?}?>
echo "<option value='". $row['CatName']."'>."</option>';
contains error and also there is no inner html for options
You can use this way for simplicity.
$CatName=$row["CatName"];
echo '<option value="'.$CatName.'">'.$CatName.'</option>';
Ok. Now I have created a new php file called getcategories.php. and this page works well. Here is the code for it:
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
$options="";
//echo "<select value='categories'>";
while($row = $result->fetch_assoc()) {
$categoryname=$row["CatName"];
// echo '<option value="'.$categoryname.'">'.$categoryname.'</option>';
// echo "</select>";
//echo "$categoryname\n";
$options .= '<option value="'.$categoryname.'">'.$categoryname.'</option>';
}
?>
How should I pull the data of options to the dropdown of html file
I am creating a page for students where they can search their result by three different option. i am having problem. Kindly guide me where i am doing mistake
<form action="do_search.php" method="post">
<table width="540" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="30"><strong>Search Criteria</strong></td>
<td></td>
<td><label for="criteria"></label>
<select name="criteria" id="criteria">
<option>Seach by Name</option>
<option>Search by Father Name</option>
<option>Search by Roll No.</option>
</select></td>
</tr>
<tr>
<td height="30"> </td>
<td></td>
<td> </td>
</tr>
<tr>
<td width="150" height="30"><strong>Enter Value:</strong></td>
<td width="20"></td>
<td width="370"><input name="value" type="text" id="value" size="40" /></td>
</tr>
<tr>
<td height="10" colspan="3"></td>
</tr>
<tr>
<td height="30"></td>
<td></td>
<td>
<input name="submit" type="submit" value="Submit" id="submit_btn"/>
<input name="reset" type="reset" value="Reset" id="reset_btn" /> </td>
</tr>
<tr>
<td colspan="3" height="10"></td>
</tr>
</table>
</form>
do.search.php
<?php
include 'authentication.php';
include 'includes/dbConnect.php';
?>
<?php
$criteria = $_POST['criteria'];
$value = $_POST['value'];
if ($value == '')
{
$myURL = 'error.php?eType=no_value';
header('Location: '.$myURL);
exit;
}
if ($criteria == "search by name")
{
$result = mysql_query( "SELECT * FROM students WHERE Name = '$value'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
}
elseif ($criteria == "search by father name")
{
$result = mysql_query( "SELECT * FROM students WHERE Father_Name = '$value'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
}
elseif ($criteria == "search by roll no.")
$result = mysql_query( "SELECT * FROM students WHERE Roll_No. = '$value'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
?>
Kindly guide me where i am doing wrong.
Your dropdown values will never have a match since <option>Seach by Name</option> will never match with $criteria == "search by name".
In your form, I suggest do something like:
<select name="criteria" id="criteria">
<option value="1">Seach by Name</option>
<option value="2">Search by Father Name</option>
<option value="3">Search by Roll No.</option>
</select>
Then in PHP, just normally compare them on if else blocks or switch.
switch($criteria) {
case '1':
// do something
break;
case '2':
// do something
break;
case '3':
// do something
break;
}
Sidenote: I strongly suggest switch to the improved version API which is mysqli or use PDO instead, and use prepared statements.
Rough example (untested):
if(isset($_POST['criteria'], $_POST['value'])) {
$columns = array(1 => 'Name', 2, 'Father_Name', 3, 'Rol_No.');
$db = new mysqli('localhost', 'username', 'password', 'database');
$criteria = $_POST['criteria'];
if(!isset($columns[$criteria])) {
// column not found
exit;
}
$column_selected = $columns[$criteria];
$value = '%' . $_POST['value'] . '%';
$select = $db->prepare("SELECT * FROM students WHERE $column_selected LIKE ? ");
$select->bind_param('s', $value);
$select->execute();
if($select->num_rows > 0) {
// found
} else {
// none found
}
}
First of all brother $_POST['criteria'] get empty values And whenever you write a search query, always use LIKE clause.
Here is the Solution Rizwan sahib:
<select name="criteria" id="criteria">
<option name="name">Seach by Name</option>
<option name="father">Search by Father Name</option>
<option name"roll">Search by Roll No.</option>
</select>
<?php
$result = '';
if ($criteria == "name")
{
$result = mysql_query( "SELECT * FROM students WHERE Name LIKE '%$value'%" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
}
elseif ($criteria == "father")
{
$result = mysql_query( "SELECT * FROM students WHERE Father_Name LIKE '%$value%'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
}
elseif ($criteria == "roll"){
$result = mysql_query( "SELECT * FROM students WHERE Roll_No. LIKE '%$value%'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
}
$row = mysql_fetch_array($result);
?>
The "%" sign is used to define wildcards (missing letters) both before and after the pattern.
Hope you find your solution
I tried to create a button which the function is to sort data either descending or ascending. However, I don't have idea how to do it
I did some research in internet, but none of them give the answer.
anyone know how to do it or some source code which can be a references???
this is my code
test.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Data Mining</title>
</head>
<body>
<form action="showDB.php" method="post">
<table border="0">
<tr>
<th>test</th>
</tr>
<tr>
<td>Select Foreign Agent Country</td>
<td></td>
<td>
<select name="country">
<option value="US">United States</option>
<option value="NZ">New Zealand</option>
<option value="JP">Japan</option>
</select>
</td>
</tr>
<td>
<input type="submit" name="formSubmit" value-"Submit">
</td>
</table>
</form>
</body>
</html>
showDB.php
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "");
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == 'US') {
// query to get all US records
$query = mysql_query("SELECT * FROM auip_wipo_sample WHERE applicant1_country='US'");
}
elseif($country == 'NZ') {
// query to get all AUD records
$query = mysql_query("SELECT * FROM auip_wipo_sample WHERE applicant1_country='NZ'");
}elseif($country == 'JP') {
// query to get all AUD records
$query = mysql_query("SELECT * FROM auip_wipo_sample WHERE applicant1_country='JP'");
} else {
// query to get all records
$query = mysql_query("SELECT * FROM auip_wipo_sample");
}
//fetch the result
Print "<table border cellpadding=3>";
//ascending descending button
Print "<tr><th colspan='2'><input type='submit' name='asc_sort' value-'Asc'></input></th></tr>";
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print "<td>".$row['invention_title'] . "</td>";
Print "<td>".$row['invention-title'] . " </td></tr>";
}
//sorting the data, I got from internet but doesn't work
if(isset($_POST['asc_sort']) && !empty($_POST['asc_sort']) && $_POST['asc_sort']==1)
{
$query = "SELECT * FROM auip_wipo_sample ORDER BY invention_title ASC";
}else{
$query = "SELECT * FROM auip_wipo_sample ORDER BY invention_title DESC";
}
Print "</table>";
?>
Change this:
Print "<tr><th colspan='2'><input type='submit' name='asc_sort' value-'Asc'></input></th></tr>";
To
Print "<tr><th colspan='2'><input type='submit' name='asc_sort' value='Asc'></input></th></tr>";
And this
if(isset($_POST['asc_sort']) && !empty($_POST['asc_sort']) && $_POST['asc_sort']==1)
to
if(isset($_POST['asc_sort']) && !empty($_POST['asc_sort']))
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Data Mining</title>
</head>
<body>
<form action="showDB.php" method="post">
<table border="0">
<tr>
<th colspan="3">test</th>
</tr>
<tr>
<td>Select Foreign Agent Country</td>
<td>
<select name="country">
<option value="US">United States</option>
<option value="NZ">New Zealand</option>
<option value="JP">Japan</option>
</select>
</td>
<td><input type="checkbox" name="asc" value="1" /> Ascending?</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" name="formSubmit" value-"Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
Few things:
You were pulling a query statement in the middle of a while where
you're still retrieving the previous statement. This would require
pulling the data into multiple arrays and then processing.
You should be using something like pdo or mysqli for this, but here's an
example with your current methods.
Also you were using isset on POST... if POST has anything in it, it will return as set.
Referencing a POST variable that is not set will cause an error, So I'm checking to make sure that country is set then I'm provided a NULL answer to the switch.
Example Code:
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "");
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if(!empty($_POST['formSubmit'])&&($_POST['formSubmit']=="Submit")&&(!empty($_POST['country']))){
$country = $_POST['country'];
} else {
$country = '';
}
if(!empty($_POST['asc']))
{
$append = " ORDER BY invention_title ASC";
}else{
$append = " ORDER BY invention_title DESC";
}
switch($country){
case 'US':
$query = "SELECT * FROM auip_wipo_sample WHERE applicant1_country='US'$append";
break;
case 'NZ':
$query = "SELECT * FROM auip_wipo_sample WHERE applicant1_country='NZ'$append";
break;
case 'JP':
$query = "SELECT * FROM auip_wipo_sample WHERE applicant1_country='JP'$append";
break;
default:
//all records
$query = "SELECT * FROM auip_wipo_sample$append";
}
//query the database
if($result = mysql_query($query)){
//fetch the result
print "<table border cellpadding=3>";
while($row = mysql_fetch_array($result))
{
print "<tr>";
print "<td>".$row['invention_title'] . "</td>";
print "<td>".$row['invention-title'] . " </td></tr>";
}
//sorting the data, I got from internet but doesn't work
print "</table>";
} else {
//For Testing
echo "Query Failed:<br />$query";
}
?>