Hopefully the last question as I am not 100% sure how to solve this one.
I did see a similar question , but it does not really reflect my question and the other question is quite difficult to follow , so please see this as a original question and not a duplicate..
So on my website someone carried out a search from a search bar using the 'POST' method , teh search results show all whiskies in the databse. I have a number of whiskies with the same name but with different dates and prices. I would like it just to show one of each type that was searched for rather than all of them. I have attahced a clip of the databse. Really appreciate the help
Thanks
Index.php
</head>
<?php
$page='index';
include('header.php');
include('navbar.php');
?>
<script type="text/javascript">
function active(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == 'Search for your whisky here'){
search_bar.value=''
search_bar.placeholder= 'Search for your whisky here'
}
}
function inactive(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == ''){
search_bar.value='Search for your whisky here'
search_bar.placeholder= ''
}
}
</script>
<body>
<div class="third_bar">
<div class="background_image">
</div>
<div class="form"><form action= "search.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div> </div>
</body>
</div>
<?php include ('footer.php');
?>
Search.php
<?php
$page='search';
include('header.php');
include ('navbar.php');
echo "<br>";
include ('connect.php');
if (isset ($_POST['search'])) { //the 'search' refers to the 'search' name=search on the index page and makes does something when the search is pushed.
$search = $_POST['search'];
$search = "%" . $search . "%"; // MySQL wildcard % either side of search to get partially matching results
// No wildcard if you want results to match fully
} else {
header ('location: index.php');
}
$stmt = $conn->prepare("SELECT * FROM test_db WHERE name LIKE :name ORDER BY name ASC"); // Use = instead of LIKE for full matching
$stmt->bindParam(':name', $search);
$stmt->execute();
$count = $stmt->rowCount(); // Added to count no. of results returned
if ($count >= 1) { // Only displays results if $count is 1 or more
echo "<div class='results_found'>";
echo $count;
echo " results found<br>";
echo "</div>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='results'>";
echo "<div class='result_name'>";
echo "<b>Whisky Name:</b><br>";
echo "<a href='details1.php?id={$row['lot_id']}' >{$row['name']}</a>";
echo"<br>";
echo "</div>";
echo "</div>";
}
} else {
echo " Sorry no records were found";
}
?>
</htm
Related
This is just for a school project and it feels like such a simple problem but every time i google what seems to be the problem i just cant understand most of the answers
<form action="bookResults.php" method="get">
<h4>Book Search</h4>
<label for="searchType">Search Type:</label>
<select name="searchType" id="searchType">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
</select><br>
<label for="searchTerm">Search Term:</label>
<input type="text" name="searchTerm"><br>
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
</form>
this is the form in html
<?php
if (!isset($_GET['searchType'])) {
$searchType = $_GET['searchType'];
if (!isset($_GET['searchTerm'])) {
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
if(!$searchType || $searchTerm){
echo 'You have not entered search details. Please go back and try again';
}else{
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like '%".$searchTerm."%'";
$result = $mysqli->query($query);
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
and this is my incomplete php code, the goal is to let the user choose with a dropdown menu between 3 categories in my book table in my database. its either they search by Author, title or isbn. But i cant even get to that part without getting this "undefined array key" error in the first few lines
EDIT: The next project i was supposed to work on involved prepared statements, the school just wanted us to use manual insertions i guess
You don't use an anchor to submit a form. You have to use a submit button. So change
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
to
<button class="btn btn-primary" type="submit" role="button">Submit</button>
When you use the anchor, none of the form fields are added to the URL.
You also have some problems in your PHP logic.
You can combine the tests for whether the parameters are set and properly filled in by using !empty(). You can test both parameters at once, rather than using nested if statements.
Your code is also wide open to SQL injection. You should use a prepared statement with parameters rather than substituting the variable into the SQL.
<?php
if (!empty($_GET['searchType']) && !empty($_GET['searchTerm'])) {
$searchType = $_GET['searchType'];
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like CONCAT('%', ?, '%')";
$statement = $mysqli->prepare($query);
$statement->bind_param("s", $searchTerm);
$statement->execute();
$result = $statement->get_result();
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
} else {
echo 'You have not entered search details. Please go back and try again';
}
So I am wanting the user to be able to search by either keyword or ID number. If they search "test" right now for example it will pull all the entries with test which is what I want it to do for the keyword part of the search. However, I also want the user to be able to search my specific a specific ID# and just pulling that specific entry. I am unsure how I would go about doing this. I tried doing some sort of OR statement but it did not pull any entries.
Search box form
<div class ="search" id="browse">
<p> Find your appointment below or search by keyword</p>
<form id="" class="searchbar" action="searchAppt.php" method="get">
<input type="text" name="terms" size="40" class = "sbar" placeholder="Search by issue keyword or ID" oninput="validity.valid||(value='');"
onblur="if (this.value == '') {
this.value = 'Enter keyword or ID';
}"
onfocus="if (this.value == 'Enter keyword or ID') {
this.value = '';
}"/>
<button type="submit" class = "btn">Search</button>
</form>
</div>
searchAppt.php
if (filter_has_var(INPUT_GET, "terms")) {
$terms_str = filter_input(INPUT_GET, 'terms', FILTER_SANITIZE_STRING);
} else {
echo "There were no appointments found.";
include ('includes/footer.php');
exit;
}
//explode the search terms into an array
$terms = explode(" ", $terms_str);
$sql = "SELECT * FROM appointments WHERE 1";
foreach ($terms as $term) {
$sql .= " AND email = '". $_SESSION['email'] ."' AND issue LIKE '%$term%' OR id ='%term%'
";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<br /><br /><center><h1>My Ticket(s)</h1><br />
<div class='table'>
<div class='tr'>
<div class='td'><b>Ticket #</b></div>
<div class='td'><b>Issue</b></div>
<div class='td'><b>Date</b></div>
<div class='td'><b>Ticket Details</b></div>
</div>";
// output data of each row
while($row = $result->fetch_assoc()) {
$starttimepast = strtotime($row["start_time"]); //converts date time received from MySQL into a string
$datepast = date("m/d/y", $starttimepast);
echo "<div class='tr'>
<div class='td'>".$row["id"]."</div>
<div class='td'>".$row["issue"]."</div>
<div class='td'>".$datepast."</div>
<div class='td'><form action='ticketdetails.php' method='post'>
<input type='hidden' name='id' value='".$row["id"]."'>
<input type='submit' value='Ticket Details'></form>
</div>
</div>";
}
echo "</div>";
echo "<br /><center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
include ('includes/footer.php');
} else {
echo "<br /> <br /><center><h3>Your search <i>'$terms_str'</i> did not match any appointments</h3></center>";
echo "<center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
echo "<br />";
exit;
}
?>
<?php
// clean up resultsets when we're done with them!
$query->close();
// close the connection.
$conn->close();
Perhaps it will help to explicitly group the terms:
$sql = "SELECT * FROM appointments WHERE email = '" . S_SESSION['email'] . "'";
$exprs = array();
foreach ($terms as $term) {
$exprs[] = "(issue LIKE '%$term%' OR id LIKE '%$term%')";
}
if (!empty($exprs)) {
$sql .= ' AND (' . join(' OR ', $exprs) . ')';
}
The result in this case will include records that matched any of the terms.
Note: It would be good to use a DB API like laravel/PDO/mysqli to simplify the query building and properly escape the values.
I am doing a project and need some help please :) (full code at bottom)
The project needs to be accessed with PDO.
I need search results to appear on the same page as the search was entered.
This below doesnt seem right to me using GET instead of POST.. is this correct?
This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
How do i do that?
Also my second problem is I can not get the search form to search more than one field in a table. It just wont let me. I cant use this bit of code either
%'.$searchterm.'%
as it wont give me any feedback from the search. So i am using the
:searchterm
in
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm OR nationality ");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
Here is my full code:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_POST['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
$conn=NULL;
?>
In good practices, use POST to send params when user SEND something to the server that will change data on the server (store in db for exemple or send an email). Use GET when user RETRIEVE something from the server, to read data (query a db). So prefer GET here.
To solve your issue, simply enclose the whole code that process the research in a "if(isset($_GET['search'])){}" section as below:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_GET['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
if(isset($_GET['search'])){
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>";
}
$conn=NULL;
}
?>
This below doesnt seem right to me using GET instead of POST.. is this correct? This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
It depends on whenever you want to use GET or POST. POST is more secure, so for submitting a form I'm always using POST. In that case you can leave this code:
if(isset($_POST['search'])){
echo 'Search';
}
You do need to change the form's action type to POST:
<form action="index.php" method="post">
....
Then add the end you need to get the search value from the POST instead of GET, because we changed the action type.
$searchterm = $_POST['search'];
So i figured this out and
<!-- HTML FORM SEARCH BAR -->
<form action="index.php" method="post">
<label for="enteredterm">Enter a Weight-class or a Nationality:</label>
<input type="text" name="enteredterm">
<input type="submit" name="search">
</form>
<!-- HTML FORM SEARCH BAR -->
if(isset($_POST['search'])){
$enteredterm = $_POST['enteredterm'];
if ($enteredterm ===""){
echo "error, enter something.";
} else {
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :enteredterm OR nationality LIKE :enteredterm or lastname LIKE :enteredterm ORDER BY year");
$stmt->bindValue(':enteredterm','%'.$enteredterm.'%');
$stmt->execute();
$count= $stmt->rowCount();
echo "You entered ".$enteredterm." and returned ";
if($count <= 1){
echo $count." result.";
}else{
echo $count." results.";
}
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
I followed a tutorial on how to make a search bar functional and I am not seeing what I'm doing wrong. I am trying to give users the option to search for products. The end result is everything is being out-putted as 'Array'. The correct amount of search results show up.
My search bar is on my index page.
<form class="searchbar" action="/searchresults" method="POST">
<input class="inputsearchbar" type="text"
name="search" size="50">
<input class="searchButton" type="submit" value="Search" name="submit">
</label>
</form>
I then have a page called searchresults.php where my results are outputted to. I'm pulling from my products table in my database.
I have this at the top of the file..
if(!isset($_POST['search'])) {
header("Location:index.php");
die($e->getMessage());
}
$con = mysqli_connect("localhost", "root", "", "bfb");
$search_sql = "SELECT * FROM products WHERE name LIKE '%" . $_POST['search'] . "%' OR description LIKE '%" . $_POST['search'] . "%'";
$search_query=mysqli_query($con, $search_sql);
if (mysqli_num_rows($search_query)!=0) {
$search_rs=mysqli_fetch_assoc($search_query);
}
?>
Followed by this in the body to output the results...
<h1>Search Results</h1>
<?php
if(mysqli_num_rows($search_query)!=0) {
do { ?>
<p><?php echo $search_rs=['name']; ?></p>
<p><?php echo $search_rs=['description']; ?></p>
<?php } while ($search_rs=mysqli_fetch_assoc($search_query));
} else {
echo"Sorry, no results were found. Please try again.";
}
?>
</div>
Why are all of my results displaying as 'Array' and how can I correct this?
take out the extraneous equal sign (=)
<?php echo $search_rs['name']; ?>
You have to use $_search_rs['name'] . Remove the extra '=' symbols.
Edit your PHP code as follows.
<h1>Search Results</h1>
<?php
if(mysqli_num_rows($search_query)!=0) {
do { ?>
<p><?php echo $search_rs['name']; ?></p>
<p><?php echo $search_rs['description']; ?></p>
<?php } while ($search_rs=mysqli_fetch_assoc($search_query));
} else {
echo"Sorry, no results were found. Please try again.";
}
?>
Can someone have a look at my code Ive finally got working after 2 days and lots of help from here - thank you!
There are a few tweaks i would like to do on it -
for the transaction ID, if i search for any letter in the transaction id, i am shown records - I only want it to show me a record if the FULL transaction ID has been entered and matches the record in the database. Transaction id example: 87K07228GD157974M
if you want to retrieve your code, you must type in your name, email and transaction date, this works perfect BUT the time is also included with the date but i don't want anyone to have to enter the time as well ONLY the date i.e.....
you currently have to enter: 2013-03-07 01:39:23 - but i want to enter in the format of DD/MM/YY - is this possible?
I also don't know if the code is secure also, any advice would be appreciated.
Thanks,
here is the code:
findme.html
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search Transaction ID</h2>
<form name="search" method="post" action="findme.php">
Seach for: <input type="text" name="find" />
<input type="submit" name="search" value="Search" />
</form>
OR
<h2>Search Name, E-Mail & Transaction Date</h2>
<form name="search" method="post" action="findme1.php">
Full Name (on paypal account) <input type="text" name="name" /> <br><br>
Paypal E-Mail Address <input type="text" name="email" /> <br><br>
Transaction Date - DD/MM/YY <input type="text" name="date" />
<input type="submit" name="search" value="Search" /><br><br>
If searching via Name, E-Mail & Transaction date, all fields must be completed to obtain your code.
</form>
</body>
</html>
findme.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search Results:</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// Otherwise we connect to our Database
mysql_connect("location.com", "ipn", "password!") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): </b> " .$find;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
findme1.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search Results:</h2><p>";
//If they did not enter a search term we give them an error
if ($name == "")
if ($email == "")
{
echo "<p>Please enter Full Name, E-Mail Address & Transaction Date EXACTLY how they appear on your PayPal Account...";
exit;
}
// Otherwise we connect to our Database
mysql_connect("location.com", "ipn", "password") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$name = mysql_query("SELECT * FROM ibn_table WHERE iemail = '$email' AND iname = '$name' AND itransaction_date = '$date'");
//And we display the results
while($result = mysql_fetch_array( $name ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): " .$name;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($name);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
Fields in my database are:
iname
iemail
itransaction_id
ipaymentstatus
itransaction_date
Thanks!
As stated in comment for transaction ID you have :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
what LIKE with %$find% does is match any part from transaction ID with $find that is why you get results with single letter. Change that to :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id = '$find'");
for date issue you can decide what to take from user like you stated date then for example :
if you take :
$date = "12-11-2012"; //(dd-mm-yyyy)
$split = explode("-", $date);
then you can use this to generate SQL date/time format :
$sql_date = date("Y-m-d h:i:s", mktime(0, 0, 0, (int) $split[1], (int) $split[0], (int) $split[2]))
and in sql query :
transaction_date LIKE '$sql_date%'
And at last don't use mysql_* it is deprecated. Instead use mysqli.