PHP Search MySQL Database - Multiple Search Variables - php

For all those that care, the if not empty statement worked for me
I'm new to SQL and PHP and am trying to implement a search functionality to grab data from a MySQL database that deals with wines.
I have figured out how to do a query where there is one search variable, and I have figured out how to do it with two search variables, i'm sure i could continue on that pattern - but what i'd like to do is implement a search function that can search based on what the user inputs into the variables (That means, the user must enter at least one value, and the search will grab fields relevant to the search variable).
Say for example I have these search variables:
wine name - (user can leave this blank or enter a value)
wine type - (user enters a value)
year - (user can leave this blank or enter a value)
Based on how many variables the user enters will dictate how refined the search is.
I've tried searching the forums but can't seem to find anything. Apologies if my formatting, or question is wrong. Would appreciate any help or a point in the right direction, thanks!
Here is my code so far that works if the user enters both variables 'wineName' and 'wineryName'. Tried using isset to trigger some sort of switch, but i don't think i'm on the right track.
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Answer Page</title>
</head>
<body bgcolor="white">
<?php
function showerror() {
die("Error " . mysql_errno() . " : " . mysql_error());
}
require 'db.php';
// Show all wines in a region in a <table>
function displayWines($connection, $query, $wineName) {
// Run the query on the server
if (!($result = # mysql_query ($query, $connection))) {
showerror();
}
// Find out how many rows are available
$rowsFound = # mysql_num_rows($result);
// If the query has results ...
if ($rowsFound > 0) {
// ... print out a header
print "You searched for $wineName with a region of $wineryName <br><br>";
// and start a <table>.
print "\n<table>\n<tr>" .
"\n\t<th>Wine ID</th>" .
"\n\t<th>Wine Name</th>" .
"\n\t<th>Winery Name</th>" .
"\n\t<th>Year</th>\n</tr>";
// Fetch each of the query rows
while ($row = # mysql_fetch_array($result)) {
// Print one row of results
print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
"\n\t<td>{$row["wine_name"]}</td>" .
"\n\t<td>{$row["winery_name"]}</td>" .
"\n\t<td>{$row["year"]}</td>\n</tr>";
} //end while loop body
//finish table
print "\n</table>";
} //end if $rowsFound body
//Report how many rows were found
print "<br>{$rowsFound} records found matching your criteria<br>";
} //end of function
// Connect to the MySQL server
if (!($connection = # mysql_connect(DB_HOST, DB_USER, DB_PW))) {
die("Could not connect");
}
//get user data
$wineName = $_GET['wineName'];
$wineryName = $_GET['wineryName'];
if (!mysql_select_db(DB_NAME, $connection)) {
showerror();
}
//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
if (isset($wineName)) {
$query .= " AND wine_name = '{$wineName}'";
}
if (isset($wineryName)) {
$query .= " AND winery_name = '{$wineryName}'";
}
//order the list
$query .= " ORDER BY wine_name";
//run query, show results
displayWines($connection, $query, $wineName);
?>
</body>
</html>

//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
if (isset($wineName)) {
$query .= " AND wine_name LIKE '%$wineName%'";
}
if (isset($wineryName)) {
$query .= " AND winery_name LIKE '%$wineryName%'";
}
//order the list
$query .= " ORDER BY wine_name";
//run query, show results
displayWines($connection, $query, $wineName);

First of all, change your INPUT's names to an array, e.g.
<input name="wine[wineName]" ...>
<input name="wine[wineryName]" ...>
Now you have to change the way you get the user data:
// Define an array of allowed fields ("whitelist")
$fields = array('wineName', 'wineryName');
// Get the fields given by the user
$wine = array();
foreach($fields as $field)
if (isset($_GET['wine'][$field]))
$wine[$field] = mysql_real_escape_string($_GET['wine'][$field]);
// ... your code here ...
//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
foreach ($wine as $field => $value) $query .= " AND ".$field." = '".$value."'";
One important hint: NEVER use user given input in your query without escaping! (see http://php.net/manual/en/function.mysql-real-escape-string.php)

Please have a look at the following lines:
print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
"\n\t<td>{$row["wine_name"]}</td>" .
"\n\t<td>{$row["winery_name"]}</td>" .
"\n\t<td>{$row["year"]}</td>\n</tr>";
It should be
print "\n<tr>\n\t<td>{$row['wine_id']}</td>" .
"\n\t<td>{$row['wine_name']}</td>" .
"\n\t<td>{$row['winery_name']}</td>" .
"\n\t<td>{$row['year']}</td>\n</tr>";
instead. Your double quotes for the array key are closing your string.
Note:
Because your tutor has said to use the deprecated mysql_* functions you can't do much about it. But please bear in mind, that you better should use parameterized prepared statements and bind your input values to the parameters (with PDO or mysqli).

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Search Form Ability To Ignore Blank Fields

I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;

Use multiple keywords to display results from 2 tables

EDIT......I have a normalized database which is based on a learning environment.
I would like to be able to search for a selection of keywords which are in a table called 'C_Search' and use them to pull up the course details which stored in 'C_Info'. I have a basic search function but it is driving me crazy with how to get the keywords involved as I am new to all this and trying to learn as I go along...sometimes we need help
These are the relevant tables and the fields in them.
C_Info
Course_ID
Course_Name
C_Description
C_Duration
C_Cost
C_Entry_Req
C_Assessment_Type
C_Progression
C_Type
C_Search
Course_ID
C_Key_Words
C_NLC_Ref_No
Awarding_Body
C_UCAS_Code
There are a list of keywords separated by a coma. I would like to use them to allow users to search the database for available courses.
I know I have posted this before but some of the answers were confusing and I'm struggling to learn as it is.
<?php
mysql_connect ("localhost", "jimbooth_test","test1") or die (mysql_error());
mysql_select_db ("jimbooth_groupproject");
// first part of the main query (with dummy WHERE operator so you can then use AND operators)
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
// query the keywords
$res1 = mysql_query("select keyword from C_Search") or trigger_error(mysql_error()
// loop through rows and add conditions to the main query
while ($keyword_row = mysql_fetch_assoc($res1)) {
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
}
$res2 = mysql_query($query);
die($query);
if (mysql_num_rows($res2) <= 0) {
// no results
echo 'Sorry, No results found.';
} else
while ($row = mysql_fetch_array($res2)){
echo '<br/> <B>Course Title:</B> '.$row['Course_Name'];
echo '<br/> <B>Course Info:</B> '.$row['C_Description'];
echo '<br/> <B>Duration:</B> '.$row['C_Duration'];
echo '<br/> <B>Entry Requirements:</B> '.$row['C_Entry_Req'];
echo '<br/> <B>Course Cost: '.$row['C_Cost'];
echo '<br/> <B>Course Progression: '.$row['C_Progression'];
echo '<br/><br/>';
}
?>
Your SQL query is failing:
"select keyword from C_Search"
Which means that $res1 is not a result. Instead, it is a boolean FALSE value. mysql_fetch_assoc expects a resource. Are you sure that C_Info exists and that you haven't made any typos?
Try adding:
$res1 = mysql_query("select keyword from C_Search") or trigger_error(mysql_error());
Tell us if any errors are spit out onto the screen.
PS: The people telling you remove the WHERE 1 don't seem to realize that you're doing this:
$query .= " AND C_Description like '%{$keyword_row['keyword']}%'";
further down the line. Although I do agree that you should probably use WHERE 1 = 1 as that is the most commonly used "always true" condition that gets used when a query is being constructed dynamically :)
I think you connection to DB is not set properly kindly check the connection by
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Searching MySQL with PHP

I am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :)
(index.php)
<form name="search" action="search.php" method="get">
<div align="center"><input type="text" name="q" />
<p><input type="submit" name="Submit" value="Search" /></p>
</form>
(search.php)
<?php
//Get the search variable from URL
$var=#&_GET['q'];
$trimmed=trim($var); //trim whitespace from the stored variable
//rows to return
$limit=10;
//check for an empty string and display a message.
if($trimmed=="")
{
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var))
{
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "select * from events where artist_name like \"%trimmed%\" order by date";
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row=mysql_fetch_array($result)) {
$title = $row["artist_name"];
echo"$count.) $title";
$count++;
}
$currPage = (($s/$limit) + 1;
echo"<br />";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
print" <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news = $s+$limit;
echo " Next 10 >>";
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Your where clause is goofy...try changing it to:
WHERE artist_name like '%$trimmed%'
just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
$query = "select * from events where artist_name like '%$trimmed%' order by date";
In order to use the variable $trimmed in a query, escape it first. Otherwise, your script will be vulnerable to SQL injection attacks, and attackers will be able to run almost any query against your database. This problem is exacerbated by the fact that you are connecting to MySQL as root. Never ever do this in a production environment.
Also, to expand a variable in a string, you should include the $ character before the variable name.
$trimmed = trim($var);
$escaped = mysql_real_escape_string($trimmed);
$query = "select * from events where artist_name like \"%$escaped%\" order by date";
Your code still looks all over the place. I think the main reason it wasn't working was the mixing of " and '. You need to escape variables before you use them in your queue. mysql_real_escape_string is the lowest form of escaping you should be using. I'd recommend you have a look at PDO though.
<?php
//Get the search variable from URL
$var = $_GET['q'];
$trimmed = mysql_real_escape_string(trim($var)); //trim whitespace and escape the stored variable
//rows to return
$limit = 10;
//check for an empty string and display a message.
if($trimmed == "") {
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var)){
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "SELECT * FROM events WHERE artist_name LIKE %$trimmed% ORDER BY DATE";
$numresults = mysql_query($query);
$numrows = mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0){
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank"\ title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row = mysql_fetch_array($result)) {
$title = $row['artist_name'];
echo $count.' '.$title;
$count++;
}
$currPage = (($s/$limit) + 1;
echo "<br>";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
echo ' <a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'"><&lt';
echo 'Prev 10</a> ';
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news=$s+$limit;
echo ' Next 10 >>';
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo '<p>Showing results '.$b.' to '.$a.' of '.$numrows.'</p>';
?>
You are missing a $ symbol. I think
$var=#&_GET['q'];
should probably be
$var=#$_GET['q'];
unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it)
$var=& $_GET['q'];
I would be tempted to write it a bit more like this.
if (!isset($_GET['q'])) {
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
$trimmed = trim($_GET['q']);
if($trimmed=="") {
echo"<p>Please enter a name.</p>";
exit;
}
Also as Chad mentioned, an sql injection would be simple since you arent cleaning input before performing DB actions with it.
try adding
foreach($_REQUEST as $param => $value)
{
$_REQUEST[$param]=mysql_real_escape_string($value);
}
This way you escape all the user input so the user cant tamper with the db. Read more about this method and sql injection in the docs here:
http://us2.php.net/mysql_real_escape_string

Categories