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
Related
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.
This question already has answers here:
Create PHP array from MySQL column
(12 answers)
Closed 22 days ago.
I tried to create a simple select dropdown menu from MySQL database. However, it does not work on my code.
Here is my code:
<?php
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
$count=0;
while ( $row = mysql_fetch_array($RsCourse, MYSQL_ASSOC)) {
$courseid=$row["courseid"];
$count++;
}
?>
<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> <select name="courseid">
<option value="" SELECTED>Selected Course</option>
<option value="<?php echo $courseid; ?>"><?php echo $row_RsCourse['$courseid']; ?></option>
</select>
</td>
</tr>
Any advice will be appreciated!
<?php
echo '<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> ';
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
if($totalRows_RsCourse)
{
echo '<select name="courseid"><option value="" SELECTED>Selected Course</option>';
$count=0;
while ($row = mysql_fetch_array($RsCourse, MYSQL_ASSOC))
{
$count++;
echo '<option value="'.$row['courseid'].'">'.$row['courseid'].'</option>';
}
echo '</select>';
}
else
{
echo 'No courses to show yet.'; // no rows in tbl_course
}
echo '</td>
</tr>';
?>
That was a mess, but hope you can go on from these new codes. Enjoy.
PS: this part >'.$row['courseid'].'</option> u can change to new one according to your table structure which one is not shown here.
<?php
echo '<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> ';
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
echo '<select name="courseid"><option value="" SELECTED>Selected Course</option>';
$count=0;
while ($row = mysql_fetch_array($RsCourse, MYSQL_ASSOC))
{
$count++;
echo '<option value="'.$row['courseid'].'">'.$row['courseid'].'</option>';
}
echo '</select></td>
</tr>';
?>
You can store everything in a buffer and print at once in the select below:
<?php
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$coursesHtml = "";
while ( $row = mysql_fetch_array($RsCourse, MYSQL_ASSOC)) {
$coursesHtml .= "<option value='{$row["courseid"]}'>{$row["coursename"]}</option>";
}
?>
<tr>
<td bgcolor="#CCCCCC">Course Name</td>
<td bgcolor="#dfdfdf">
<select name="courseid">
<option value="" SELECTED>Selected Course</option>
<?= $coursesHtml ?>
</select>
</td>
</tr>
PS: Avoid use , style your html well with css using padding-left: 5px; or other features;
PS2: You should not show your page/form with tables structure, use divs with flexbox.
Good Day!
Guys can you help me to check why my is it that i cannot insert records using chekbox option on table..
Please Help..
Here's My Code...
--ADDING Subject Load for Teacher HTML Form-- (studsub.php)
<form action="setsubject.php" method="post">
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
//$course=$row['course'];
//$year=$row['yearlevel'];
//$section=$row['section'];
$idnumber=$row['idnumber'];
echo '<br/>';
echo $row['lname'].", ".$row['fname'];
?>
<input type="hidden" name="studidnum" value="<?php echo $rows['idnumber']?>">
<?php }
?>
<br/><br/>
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"><label>Assign</label></th>
<th style="border-left: 1px solid #C1DAD7"> Subject ID </th>
<th>Title</th>
<th>Units</th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM tbl_cur_sub where status='1' ");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo ' <td>' . '<input type="checkbox" name="subject[]" value="'.$rows['code'].'" />' . '</td> ' ;
echo '<td style="border-left: 1px solid #C1DAD7">'.$row['code'].'</td>';
echo '<td><div align="left">'.$row['subject'].'</div></td>';
echo '<td><div align="left">'.$row['units'].'</div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<br/>
Course<br>
<select name="course" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM course");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['coursecode'].'</option>';
}
?>
</select>
<select name="yearlevel" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM tbl_yrlevel");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['yearlevel'].'</option>';
}
?>
</select>
<select name="section" class="ed">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
<br>
<br>
<input type="submit" value="Assign" id="button1">
</form>
--The Submission Page -- (setsubject.php)
<?php
include('../connect.php');
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$course = clean($_POST['course']);
$section = clean($_POST['section']);
$yearlevel = clean($_POST['yearlevel']);
$studidnum=$_POST['studidnum'];
$subject=$_POST['subject'];
$N = count($subject);
for($i=0; $i < $N; $i++)
{
mysql_query("INSERT INTO studentsubject (student, subject, section, course, level) VALUES ('$studidnum', '$subject[$i]','$section','$course', '$level')");
}
header("location: student.php");
mysql_close($con);
?>
--My Database--
TABLE: studentsubject
FIELDS: student, subject, section, course, level
Thanks IN advance for the Help..
TRY
mysql_query("SELECT * FROM tbl_cur_sub where status=1 ");
change the mysql statement...you need to differ the variable and string in the query
$result = mysql_query("SELECT * FROM student WHERE id='".$id."'");
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";
}
?>
My table has 4 columns. "isbn, author, title, price".
I want to search one of them combining all 4 fields.
Like: if author "kayle" write 4 books with same price ($50) but with different title, for that in search page, if i select author:kayle and hit search, then it shows all books with all different or may be same prices and titles. Now i want to select author:kayle and price:$50 at the same time, and hit enter. For that it will show only $50 prices books wrote by kayle and it will appear in the table with 4 rows.
I try to combine it but stuck with the second step searching query. Here is my code if any one understand what i want to do, please share it. Here is my code:
<form method="post" action="search_form.php">
<input type="hidden" name="submitted" value="true"/>
<table border="1">
<tr>
<td style="padding:3px 10px; font-weight:bold;">ISBN</td>
<td style="padding:3px;">
<input type="hidden" name="category_isbn" id="category_isbn" value="isbn"/>
: <select name='criteria_isbn' id="criteria_isbn" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT isbn FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[isbn] </option>");
}
?>
</select>
</td>
<td style="padding:3px 10px; font-weight:bold;">Author</td>
<td style="padding:3px;">
<input type="hidden" name="category_author" id="category_author" value="author"/>
: <select name='criteria_author' id="criteria_author" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT author FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[author] </option>");
}
?>
</select>
</td>
<td style="padding:3px 10px; font-weight:bold;">Title</td>
<td style="padding:3px;">
<input type="hidden" name="category_title" id="category_title" value="title"/>
: <select name='criteria_title' id="criteria_title" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT title FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[title] </option>");
}
?>
</select>
</td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['submitted']))
{
$category_isbn = $_POST['category_isbn'];
$criteria_isbn = $_POST['criteria_isbn'];
$query = "SELECT * FROM books WHERE $category_isbn LIKE '%".$criteria_isbn."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if(isset($_POST['criteria_isbn']))
{
$category_author = $_POST['category_author'];
$criteria_author = $_POST['criteria_author'];
$query = "SELECT * FROM books WHERE $category_author LIKE '%".$criteria_author."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if(isset($_POST['criteria_author']))
{
$category_title = $_POST['category_title'];
$criteria_title = $_POST['criteria_title'];
$query = "SELECT * FROM books WHERE $category_title LIKE '%".$criteria_title."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
echo "$num_rows results found";
echo "<table border= 1>";
echo "<tr> <th>ISBN</th> <th>AUTHOR</th> <th>TITLE</th> <th>PRICE</th> </tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr><td>";
echo $row['isbn'];
echo "</td><td>";
echo $row['author'];
echo "</td><td>";
echo $row['title'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";
}
}
}
?>
Thanks in advance.
try this
for first search
select* from table where author="kayle";
for second search
select * from table where author="kayle" and price="50";