Search results displaying all information in table - php

I am trying to search some data from a database and display it. However whenever I click on 'search' all the results in the table are displayed. Any way I can display only the information the user is searching?
This is the html code for the form.
<h2> Search </h2>
<form action = "search.php" method = "post" >
Search for: <input type = "text" name ="find" placeholder="Animal Type/Date"><span class="required"</span> in
<select NAME = "field">
<Option VALUE = "Animal Type"> Animal Type</option>
<Option VALUE = "dateseen"> Date Required</option>
</Select>
<input type= "hidden" name = "searching" value ="yes"/>
<input type= "submit" name = "search" value ="Search"/>
</form>
This is the PHP code I'm using.
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
//$find = strtoupper($find);
//$find = strip_tags($find);
//$find = trim($find);
$sql=mysqli_query($link, "Select * FROM Locations ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
//}
?>

For that you need to first grab the find field of your text box like this..
$searchKeyword = $_POST['find']; // Sanitize this value first !!
Next you need to pass it to your query... Change your yourcolumn to suit your column name.
$sql=mysqli_query($link, "Select * FROM Locations WHERE `yourcolumn` LIKE '%$searchKeyword%' ");
EDIT :
You could grab both fields and do a check..
if(!empty($_POST['find']) && !empty($_POST['field']))
{
//do your query like..
$searchKeyword = $_POST['find']; // Sanitize this value first !!
$searchKeyword2 = $_POST['field']; // Sanitize this value first !!
$sql=mysqli_query($link, "Select * FROM Locations WHERE `yourcolumn` LIKE '%$searchKeyword%' AND `yourcolumn2` LIKE '%$searchKeyword2%' ");
}
else
{
echo "The search criteria cannot be empty !";
}

Related

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

Php/MySQL if statement that returns information based on value selected

[page1.php]
<form action="result.php" method="POST" style='color:white;font-family: __custom;'>
<input type="text" placeholder="Search.." name="search" /><br><br>
<center>
<select name="example">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<br><br>
</center>
<input type="submit" value="GO!" id="sub"/>
</form><br><br><br>
[result.php]
<?php
$searchq = $_POST['search'] // search textbox;
//Connect to mySQL and retrieve all contacts
$conErr = "Error connecting to server or database";
$con = mysqli_connect("host", "user", "password", "database");
// Check connection
if (mysqli_connect_errno()) {
echo $connErr;
}
if ($_POST['example'] == 'C') {
echo "You chose inCludes";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information regarding Select Statement";
echo "<br>";
}
} else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
} else {
echo "Blah";
}
mysqli_close($con);
?>
</div>
What i'm trying to do is on page1.php the user searches for a keyword the chooses either A, B, or C from a dropdown. Based on the A, B, C the user goes to result.php and then the information is given based on the query.
The code above does not seem to be working [I do not get any results at all] [blank]. Please help.
If you want to search for something that ends with a string, you have to put the % wildcard at the beginning:
} else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
}
You missed the % wildcard after LIKE clause
else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
}

dropdown list and search field php

:)
I'm new here and I'm very new with php.
I am trying to make a search form with:
a dropdown list with two items: category and location;
a text field;
a search button.
It should work like this:
When "category" is selected, you enter a text and it will be searched only into categories.
When "location" is selected, your term will be searched among countries, states, zip codes.
I have a table with columns: id, name, category, country, zipcode, state.
Could somebody help me to understand why it doesn't display any results?
Here is my code:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
// retrieving search value we sent using get
$research = $_GET['research'];
// check if it has been sent, then it is ok
if ( $research == 'ok' ) {
// retrieving search value we sent using post
$search = $_POST['search'];
// check if the field has been filled
if ( $search == TRUE && $search != "" ) {
// character lenght more than 3
if ( strlen($search) >= 3 ) {
$search = mysql_escape_string(stripslashes($search));
}
if(isset($_POST['value'])) {
if($_POST['value'] == 'category') {
// query to get all categories
$query = "SELECT * FROM table_name WHERE category='$search'";
}
elseif($_POST['value'] == 'location') {
// query to get all country/state/zipcode records
$query = "SELECT * FROM table_name WHERE country='$search' OR zip_code='$search' OR state='$search'";
} else {
// query to get all records
$query = "SELECT * FROM table_name";
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
}
}
?>
Thank you very much for your help.
You need to understand how to use <select> with php.
if you have this form:
<form method='post'>
<select name='example'>
<option value='e1'>example1</option>
<option value='e2'>example2</option>
</select>
</form>
You need to print it like that:
echo $_POST['example'];
In case the user selcted example1, the value will be e1.
In case the user selcted example2, the value will be e2.
You are using in your script $_POST['value']. It's just dosen't exist.
Try this, instead:
HTML FORM:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
FORM PROCESSING:
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
/*********************************************/
/***WHY DO YOU NEED THIS RESEARCH VARIABLE?***/
/*****WHAT IS ITS PURPOSE IN THIS SCRIPT?*****/
/*********************************************/
//GET CLEAN VERSIONS OF ALL NECESSARY VARIABLES:
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM table_name WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}else if($catLocation == "location"){
$query .= " country LIKE '%" . $search . "%' OR zip_code LIKE '%" . $search . "%' OR state LIKE '%" . $search . "%'";
}
}else{
$query .= "1";
}
$sql = mysql_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysql_fetch_array($sql)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}

How to display database value in form list

I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";

Combo box connected to postgreSQL, how to?

How can I pick up values from a postgreSQL database and place them in a combo box using php?
Here is a full example:
myPHP.php
<?php
$db = pg_connect('host=localhost dbname=contacts user=contacts password=firstphp');
$query = "SELECT * FROM friends";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
$list_data = null;
while($myrow = pg_fetch_assoc($result)) {
$list_data .= "<option value=\"".$myrow['id']."\">".$myrow['name']."</option>";
}
// assign it to some var, I dont know what king of template you are using
$t->assign('LIST_DATA',$list_data);
?>
myFile.tpl
<select name="one">
{LIST_DATA}
</select>

Categories