Option Search Bar in html that searches using different attributes - php

I want to make a search bar in a table called items with two different options: IID, Type. The code is below.
<h1> Search </h1>
<form name="search" action="items.php" method="get">
Search For: <input type="text" name="item"> in
<select name = "Option">
<option value= "IID"> IID </option>
<option value= "Type"> Type </option>
</select>
<input type="submit" value="search">
</form>
The data is stored as a table called Item with attributes IID and type.
I then do a query, but I'm getting lost here on how to change the select clause.
I have the code here so that it searches for item(s) with a certain type the user inputs, but how can I also change the clause so that it corresponds to the option menu in the search bar where you can find items with IID? Would I have to write 2 different queries?
Any help would be appreciated!
<?php
//SEARCH by type
$item = ucfirst($_GET["item"]);
if($item != null){
$result = executePlainSQL("select * from item where type = '" . $item . "'");
}
else{
$result = executePlainSQL("select * from item");
}
printItem_byType($result);
//Print result
function printItem_byType($result){
echo '<table>';
echo '<tr><td>IID</td><td>Type</td></tr>';
while ($row = OCI_Fetch_Array($result, OCI_BOTH)) {
echo "<tr><td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td><a href= profile.php?type= ". $row[2] . ">" $row[2] . "</td></tr>";
}
echo '</table>';
}

//SEARCH by type
$item = ucfirst($_GET["item"]);
$option = $_GET["option"];
if($item != null){
$result = executePlainSQL("select * from item where type = '" . $item . "' and filter_by = '" . $option . "'");
}
else{
$result = executePlainSQL("select * from item");
}
then add one colum called "filter_by" on the sql table.

Related

How can we pass 2 values in PHP?

I can't pass the selected value to the listing page. When I select an option and click search, a default value passing to listing page. (Default value: last added value)
$sql = mysqli_query($con, "select * from jobregestation order by id");
while ($row = $sql->fetch_assoc()) {
$id = $row['id'];
$name = $row['JobName'];
echo "<option value=" . $id . ">" . $name . "</option>";
}
Thanks in advance.
Are you looking forward something like that ?
<?php
if(isset($_POST['submit'])){ // worked when click on serarch button
echo $_POST['exampleName'];
}
?>
<form action="" method='post'>
<select name="exampleName">
<?php
$sql = mysqli_query($con, "select * from jobregestation order by id");
while ($row = $sql->fetch_assoc()) {
$id = $row['id'];
$name = $row['JobName'];
echo "<option value=" . $id . ">" . $name . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Search"/>
</form>
<select>
<?php
foreach ($sql->fetch_assoc() as $key=>$value)
{
echo "<option value = " .$value['id'] . ">" .$value['Jobname]."</option>";
}
?>
</select>
This should work.

jquery .val remove spaced text

ok, so i have a select items in which the option comes from the database:
<select id="subject_code" name="subject_code">;
<?php
$stmt = $database->prepare('SELECT subject_code, subject_name FROM subject_schedule');
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$subj_code = $row['subject_code'];
$subj_name = $row['subject_name'];
echo "<option value=" . $subj_name . ">" . $subj_code . "</option>";
}
?>
</select>
an input box where the selected item should put its value:
<input id="subject_name" type="text" autocomplete="off" placeholder="Subject Name" name="time">
and a script where it will do the job:
$("#subject_code").on('change',function(){
//get selected option
var option = $(":selected",this);
//get its value
var value = option.val();
//get input box
var input = $("#subject_name")[0];
// set value and disable input
input.value = value;
});
the problem is whenever i select a value in which it has spaces on them, the input box only display the first word from the database.
example:
preferred output:
subject code: ENG111
subject name: Communication Arts 1
current output
subject code: ENG111
subject name: Communication
The problem is with quotes:
Replace this:
echo "<option value=" . $subj_name . ">" . $subj_code . "</option>";
With this:
echo "<option value='" . $subj_name . "'>" . $subj_code . "</option>";
jsFiddle

PHP, MYSQL and HTML FORMS not working together

I have this code but when I press the submit button No data is being transferred via Get, with the exemption on the submit.
<table cellspacing="0px">
<tr>
<td>Name</td><td>Today - <?php echo $date;?></td>
</tr>
<form method="get" action="update_reg.php">
<?php
$result = mysqli_query($con,"SELECT * FROM TABLE WHERE GROUP = 'Penguins' ORDER BY Rank, Name ");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>";
if($row['Rank'] == "a"){
$rank = "TOP ";
}
if($row['Rank'] == "b"){
$rank = "MIDDLE ";
}
if($row['Rank'] == "c"){
$rank = "SECOND ";
}
if($row['Rank'] == "d"){
$rank = "BOTTOM ";
}
if($row['Rank'] == "e"){
$rank = "";
}
echo $rank . $row['Name'] . "</td>";
$num = $num + 1;
echo "<td><input type=\"text\" class=\"today\" id=\"" . $row['id'] . "\" data-number=\"" . $num . "\" size=\"1\" maxlength=\"1\"></td></tr>";
}
?>
</table>
<input type="submit" value="submit">
</form>
For some reason this isn't working, anyone got any ideas why? Thanks in advance.
You need to add a value="" attribute and name="" attribute to your <input>s.
For example:
echo "<td><input type=\"text\" class=\"today\" id=\"" . $row['id'] . "\" name=\"" . $row['id'] . "\" data-number=\"" . $num . "\" value=\"" . $num . "\" size=\"1\" maxlength=\"1\"></td></tr>";
I'm not sure what you're trying to submit exactly, but place that in the value for the value attribute and make sure to give each one a name attribute and value. In my example, I used $num for the value and $row['id'] for the name.
None of your <input> tags have name attributes. No name, no form submission.
GROUP is a reserved keyword.
So you need to backtick it as
`GROUP`
SELECT * FROM TABLE WHERE `GROUP` = 'Penguins' ORDER BY Rank, Name
UPDATE FROM LAST COMMENT
Input need a name which is not there and if you give same name for all of them they will not work. So give a name="something[]" and on submit get the data as array

Select all if text box is empty

I have five textboxes which are associated with its own field from the my sql database. What I want to do is fetch data from the mysql database depending on what the user has entered in the text box. The problem is that if a text box is empty, it outputs no record as that the textbox is trying to post '' as a piece of data. How can I implement it so that if a textbox is empty, it will look for all (or any data) in that field. E.g if SessionID textbox is empty, then select all sessionID's. Below is my current coding:
<body>
<form action="exam_interface.php" method="post" name="sessionform"> <!-- This will post the form to its own page"-->
<p>Session ID: <input type="text" name="sessionid" /></p> <!-- Enter Session Id here-->
<p>Module Number: <input type="text" name="moduleid" /></p> <!-- Enter Module Id here-->
<p>Teacher Username: <input type="text" name="teacherid" /></p> <!-- Enter Teacher here-->
<p>Student Username: <input type="text" name="studentid" /></p> <!-- Enter User Id here-->
<p>Grade: <input type="text" name="grade" /></p> <!-- Enter Grade here-->
<p><input type="submit" value="Submit" /></p>
</form>
<?php
$username="u0867587";
$password="31may90";
$database="mobile_app";
$sessionid = $_POST['sessionid'];
$moduleid = $_POST['moduleid'];
$teacherid = $_POST['teacherid'];
$studentid = $_POST['studentid'];
$grade = $_POST['grade'];
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die("Unable to select database");
$result = mysql_query("SELECT * FROM Module m INNER JOIN Session s ON m.ModuleId = s.ModuleId JOIN Grade_Report gr ON s.SessionId = gr.SessionId JOIN Student st ON gr.StudentId = st.StudentId WHERE gr.SessionId = '$sessionid' AND m.ModuleId = '$moduleid' AND s.TeacherId = '$teacherid' AND gr.StudentId = '$studentid' AND gr.Grade = '$grade'");
$num=mysql_numrows($result);
echo "<table border='1'>
<tr>
<th>Student Id</th>
<th>Forename</th>
<th>Session Id</th>
<th>Grade</th>
<th>Mark</th>
<th>Module</th>
<th>Teacher</th>
</tr>";
while ($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['StudentId'] . "</td>";
echo "<td>" . $row['Forename'] . "</td>";
echo "<td>" . $row['SessionId'] . "</td>";
echo "<td>" . $row['Grade'] . "</td>";
echo "<td>" . $row['Mark'] . "</td>";
echo "<td>" . $row['ModuleName'] . "</td>";
echo "<td>" . $row['TeacherId'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
Thank You
The simplest way would be to build the WHERE part of the query dynamically based on what has been submitted, this way if the field in question is empty, that part of the where statement wouldn't exist.
Take this example, that has two possible inputs $_POST['foo'] and $_POST['bar']:
<?php
//bind vars to be used in filtering - if blank they are false
$foo = (!empty($_POST['foo']) ? mysql_real_escape_string($_POST['foo']) : false);
$bar = (!empty($_POST['bar']) ? mysql_real_escape_string($_POST['bar']) : false);
//base query: 1=1 will always be true and not filter anything
$query = "SELECT * FROM `my_table` WHERE 1=1"
if($foo){
$query.=" AND `foo` = ".$foo);
}
if($bar)
{
$query.=" AND `bar` = ".$bar;
}
$r = mysql_query($query);
?>
if you want a lazy solution so that you don't create the query one field at a time you can just add this:
foreach ($_POST as $key=>$value)
{
if (empty($value))
{
$_POST[$key] = '%';
}
}
before the block where you get the data from post and replace every equal sign (=) after the where in your query with the keywork LIKE
but the recommended solution would be the one that picus gave you with the note that you should filter the user input and escape it when you use it in the query
You want to Short circuit the logic if the entered value is empty e.g:
when you build your where for each predicate, rather than
AND m.ModuleId = '$moduleid'
use
AND ('$moduleid' = '' OR m.ModuleId = '$moduleid')
this should short circuit the column = value check
Build your query dynamically, and do not add empty variables to the WHERE clause of the query:
<?php
// Map database attributes to POST variables
$postVars = array(
'gr.SessionId' => 'sessionid',
'm.ModuleId' => 'moduleid',
's.TeacherId' => 'teacherid',
'gr.StudentId' => 'studentid',
'gr.Grade' => 'grade'
);
// Determine the parts of the WHERE clause
$whereParts = array();
foreach ($postVars as $attributeName => $postVar) {
if (isset($_POST[$postVar]) && !empty($_POST[$postVar])) {
$whereParts[] = $attributeName . " = " . mysql_real_escape_string($_POST[$postVar]);
}
}
// Create the WHERE clause if there are parts
$whereClause = "";
if (! empty($whereParts)) {
$whereClause = " WHERE " . implode(" AND ", $whereParts);
}
// Construct the complete query
$query = "SELECT * FROM table" . $whereClause;
EDIT:
Added a mapping from database attribute names to POST variable names, because these are not equal in the provided code in the question.

Dynamically create form elements with php

This short program is suppose find the column names of a table X, and create a form with at least one text field and one select element that contains all the names of the columns of the table. With that information, the user can perform a search on this table and further specify on which column he would like to do the search. I would like it for the user to be able to add more text fields with matching select elements, just in case he wants to refine his search.
How can I dynamically add those extra fields when ever the user press a button?
<?php
$table_name = "tablename";
mysql_connect("localhost", "root", "");
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table_name'";
$result = mysql_query($query);
$column_names="";
while($row = mysql_fetch_array($result)){
$column_names == "" ? $column_names .= $row["COLUMN_NAME"] : $column_names .= "," . $row["COLUMN_NAME"] ;
}
$column_names = explode(",", $column_names);
?>
<html>
<head>
<title>SQLSEARCH</title>
</head>
<body>
<form action="index.php" method="post">
<?php
echo "Search: <input tpe=\"text\" name=\"advtext[]\" /> in ";
echo "<select name=\"advselect[]\">";
foreach($column_names as $value)
echo "<option>" . $value . "</option>";
echo "</select>";
?>
<input type="hidden" name="searchsent" value="1" />
<input type="submit" name="searchbutton" value="Search" />
</form>
<input type="button" name="addattributes" value="Add Search Attributes" / onclick="AddSelect();">
</body>
</html>
This function adds an input element and a select element, every time the user presses the button.
function AddSelect(){
var newInput = document.createElement('input');
newInput.type='text';
newInput.name = 'advtext[]';
<?php
foreach($column_names as $value => $i){
echo "\tvar newOption" . $value . "=document.createElement('option')" . "\n";
echo "\tnewOption" . $value . ".value='" . $i . "';" . "\n";
echo "\tnewOption" . $value . ".innerHTML='" . $i . "';" . "\n\n";
}
?>
var newSelect = document.createElement('select');
newSelect.name = 'advselect[]';
<?php
foreach($column_names as $value => $i){
echo "\tnewSelect.appendChild(newOption" . $value . ")" . "\n";
}
?>
var SubmitButton = document.forms.myform.searchbutton;
document.forms.myform.insertBefore(newInput, SubmitButton);
document.forms.myform.insertBefore(document.createTextNode(" in "), SubmitButton);
document.forms.myform.insertBefore(newSelect, SubmitButton);
}
You can use innerHTML properties for your form . Otherwise use Ajax Functionality to add the extra text box to add dynamically.

Categories