Search Engine Script - Undefined variables - php

I have a small problem in my code and I can't figure out what is it..
I'm trying to make a sample search engine tool in PHP , everything works good until i've tryied to search some posts from database... When I do that , it says I don't have $header and $bio declared ...
<?php
include('connection.php');
$query =mysqli_real_escape_string($dbc, $_POST['query']);
$q = mysqli_query($dbc, "SELECT id FROM search WHERE header LIKE '%$query%' OR bio LIKE '%$query%'");
$num = mysqli_num_rows($q);
echo $num;
if(!$query){
echo "Enter a query...";
} else {
if($num != 0)
{
echo "<hr>";
while ($fetch = mysqli_fetch_assoc($q)){
$id = $fetch['id'];
$header = $fetch['header'];
$bio = $fetch['bio'];
echo "<strong>" . $header . "</strong>";
echo "<blockquote><p>" . $bio . "</p></blockquote>";
echo "<hr>";
}
} else {
echo "No results where found .. ";
}
}
?>
and the form
<div style = "width:300px; margin:auto;">
<h1> Add Search Criteria</h1>
<p> Type a header and bio below to add to search engine</p>
<p>
<input id="header" name = "header" type="text" placeholder="header" style="width:100%;">
</p>
<p>
<textarea id="bio" name="bio" cols="40" rows="7" placeholder="Write a bio.."></textarea>
</p>
<p>
<center>
<button id="submit">Submit Search</button>
</center>
</p>
<div id="add_error" style="text-align:center"></div>
<hr>
<h1>Search The Database</h1>
<p>Please type something to search to database</p>
<p>
<input name = "query" id="query" type="text" placeholder="search">
<button id="search">Search</button>
</p>
<div id="search_error">
</div>
</div>
this is what it outputs
Notice: Undefined index: header in C:\wamp64\www\mywebsite\Search\search.php on line 25
Call Stack
Time Memory Function Location
1 0.0021 242472 {main}( ) ...\search.php:0
( ! ) Notice: Undefined index: bio in C:\wamp64\www\mywebsite\Search\search.php on line 26
Call Stack
Time Memory Function Location
1 0.0021 242472 {main}( ) ...\search.php:0

Add header and bio columns in your select query.
$q = mysqli_query($dbc, "SELECT id, header, bio FROM search WHERE header LIKE '%$query%' OR bio LIKE '%$query%'");

Related

How to pass value in php

In my home page, I have a search bar with a button at the top of my page and I displayed all my songs using their title from my database underneath that.
The search bar is working fine since every song title I typed, it took me to the correct detail page.
I'm just wondering how can I also click on the song title and take me to each song detail page.
Home page
<?php
require_once '../config.php';
$sql = 'SELECT title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
//Search bar
<form action="chord/details.php" method="post" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
// Here I display all my songs from the database using their title
<?php
foreach ($songTitle as $song) {
// I'm not sure how to modify here.
echo "<a href='chord/details.php'>{$song['title']} <br> </a>";
} ?>
Details page
//This is working fine with Search Bar
<?php
require_once '../config.php';
if (isset($_POST['submit'])) {
$title = $_POST['search'];
$sql = 'SELECT * FROM song WHERE title = :title';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>
You can use the get HTTP method to send the id of the song to the details.php page and query to the database on that id.
And it's always a good practice to use the GET HTTP method for searching actions. As mickmackusa said in the comment:
$_POST is most appropriate when "writing" data server-side. $_GET is
most appropriate when "reading" data server-side.
So change the code on the Home page as below:
<?php
require_once '../config.php';
// query changed to fetch id as well
$sql = 'SELECT id , title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!-- here we change the method to get -->
<form action="chord/details.php" method="get" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
<?php
foreach ($songTitle as $song) {
// we add the id to the link
echo "<a href='chord/details.php?id={$song['id']}'>{$song['title']} <br> </a>";
}
?>
And change the detail.php like below:
<?PHP
//This is working fine with Search Bar
require_once '../config.php';
if (isset($_GET['search']) OR isset($_GET['id'])) {
$condition = "";
$value = "";
if (!empty($_GET['id'])) {
$condition = "id = :value";
$value = $_GET['id'];
}
elseif (!empty($_GET['search'])) {
$condition = "title = :value";
$value = $_GET['search'];
}
$sql = 'SELECT * FROM song WHERE ' . $condition;
$stmt = $conn->prepare($sql);
$stmt->execute(['value' => $value]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>
It's also a good idea to use LIKE for searching in the title like below:
if (!empty($_POST['search'])) {
$condition = "title LIKE :value";
$value = "%" . $_POST['search'] . "%";
}
Assuming you have an id column in the song table. You could do something like this:
<?php
require_once '../config.php';
$sql = 'SELECT id, title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute();
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
//Search bar
<form action="chord/details.php" method="post" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
// Here I display all my songs from the database using their title
<?php
foreach ($songTitle as $song) {
// I'm not sure how to modify here.
echo "<a href='chord/details.php?id=".$song['id]."'>{$song['title']} <br> </a>";
} ?>
Details page
//This is working fine with Search Bar
<?php
require_once '../config.php';
if (isset($_POST['submit'])) {
$title = $_POST['search'];
$sql = 'SELECT * FROM song WHERE title = :title';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
$row = $stmt->fetch();
} elseif (!empty($_REQUEST['id'])) {
$sql = 'SELECT * FROM song WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $_REQUEST['id']]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>

How to select certain term depending on search?

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.

Search by Keyword with PHP MYSQL

I am wanting to search by a keyword like a customer's issue. However, every time it searches it is pulling every single entry, not one that is from their issue.
I tried not using the for each and just doing a simple like, but that did not work either.
This is what is being passed.
<form id="" class="searchbar" action="searchAppt.php" method="get">
<input type="text" name="terms" size="40" class = "sbar" required value="Search by keyword" oninput="validity.valid||(value='');"
onblur="if (this.value == '') {
this.value = 'Enter keyword';
}"
onfocus="if (this.value == 'Enter keyword') {
this.value = '';
}"/>
<button type="submit" class = "btn">Search</button>
</form>
if (filter_has_var(INPUT_GET, "terms")) {
$terms_str = filter_input(INPUT_GET, 'terms', FILTER_SANITIZE_NUMBER_INT);
} 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 issue LIKE '%$term%' AND email = '". $_SESSION['email'] ."'
";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<br /><br /><center><h1>Your Ticket(s)</h1><br />
<div class='table'>
<div class='tr'>
<div class='td'><b>Ticket #</b></div>
<div class='td'><b>First Name</b></div>
<div class='td'><b>Last Name</b></div>
<div class='td'><b>Phone #</b></div>
<div class='td'><b>Building</b></div>
<div class='td'><b>Room #</b></div>
<div class='td'><b>Issue</b></div>
<div class='td'><b>Appt. Start Time</b></div>
<div class='td'><b>Appt. End Time</b></div>
<div class='td'><b>Ticket Details</b></div>
</div>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='tr'>
<div class='td'>".$row["id"]."</div>
<div class='td'>".$row["fname"]."</div>
<div class='td'>".$row["lname"]."</div>
<div class='td'>".$row["phonenum"]."</div>
<div class='td'>".$row["building"]."</div>
<div class='td'>".$row["room"]."</div>
<div class='td'>".$row["issue"]."</div>
<div class='td'>".$row["start_time"]."</div>
<div class='td'>".$row["end_time"]."</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>";
} else {
echo "<br /> <br />Your search <i>'$terms_str'</i> did not match any appointments";
It brings up every single appointment rather than the ones that have an issue similar to the keyword search. I feel like I'm just overlooking something with the select statement. Any help would be greatly appreciated.
Your problem is in your call to filter_input. You are specifying a filter of FILTER_SANITIZE_NUMBER_INT, but passing a space separated list of words. As a result, the output of filter_input is an empty string (since with that flag it strips everything but +/- and digits from the input), and so no conditions get added to your query. You probably want to use FILTER_SANITIZE_STRING instead.

Search Bar with Location dropdown sumit both results - PHP / mySQL

I have a basic search bar that searches my database using keywords (k). I am trying to submit both location and search result but the problem is when I submit the search results I get "search.php?k=builder&k=New+York" and not "search.php?k=builder+New+York" how do I correct this?
HTML
<form action="search.php" method="get" style="margin:0 auto; text-align:center;">
<input type="text" name="k" size="10" style="width:40%;"/>
<div id="the-basics">
<input class="typeahead" type="text" name="k" placeholder="States of USA">
</div>
<input type="submit" value="Search" style="width:100px;">
</form>
Search Bar PHP Code:
<?php
if(!empty($_GET['k'])){
//if search bar is empty
}else{
echo "'<meta http-equiv='refresh' content='0;url=index.php'>";
//redirect back to index.php
}
$k = $_GET['k']; //k stands for keyword
$i = 0;
$terms = explode(" ", $k);
$query ="SELECT * FROM record WHERE ";
foreach ($terms as $each) {
$i++;
if ($i == 1)
$query .= "company_name LIKE '%$each%' " . "OR website LIKE '%$each%' " . "OR email LIKE '%$each%' " . "OR tel LIKE '%$each%' " . "OR description LIKE '%$each%'" . "OR location LIKE '%$each%'" . "OR description LIKE '%$each%'";
}
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('DB_name');
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)) { { ?>
..........search result shows here........
Hi you need appaly some JS
<script>
function submitForm(obj){
var search = $('input[name="k"]).val();
var state= $('#state').val();
$('input[name="k"]).val(search+" "+state )
obj.submit();
}
</script>
<form action="search.php" method="get" style="margin:0 auto; text-align:center;" onsubmit=submitForm(this)>
<input type="text" name="k" size="10" style="width:40%;"/>
<div id="the-basics">
<input class="typeahead" type="text" id="state" placeholder="States of USA">
</div>
<input type="submit" value="Search" style="width:100px;">
</form>

Updating Form with MYSQL data

I am new to PHP and want to create a form where the user inserts data into the form (which works) and then that gets stored on MYSQL DB (that works), now the data has to be displayed and then must be able to modify certain records, now I have the part where the records shows and also the "edit" button, but something went wrong somewhere as the same record keeps appearing, so I guess something is wrong with my code :(
Please help:
Here is the index.php code:
<?php
include('dbinfo.php');
$sql="SELECT * FROM stats";
$result = mysql_query($sql, $db) or die (mysql_error());
$pageTitle = "My Stats Database";
include("header.php");
print <<<HERE
<h2> My Contacts</h2>
Select a Record to update add new stat.
<table id="home">
HERE;
while ($row=mysql_fetch_array($result)){
$id=$row["id"];
$type=$row["type"];
$depthead=$row["depthead"];
$person=$row["person"];
$descr=$row["descr"];
$recdate=$row["recdate"];
$tolog=$row["tolog"];
$senttorev=$row["senttorev"];
$recfromrev=$row["recfromrev"];
print <<<HERE
<tr>
<td>
<form method="POST" action="updateform.php">
<input type="hidden" name="sel_record" value="$id">
<input type="submit" name="update" value=" Edit " </form>
</td>
<td><strong> Description: </strong>$descr,<p> <strong>Type: </strong>$type</p> <p><strong> Department Head: </strong>$depthead</p>
<strong> Test Analyst: </strong> $person<br/></td>
HERE;
}
print "</tr></table></body></html>";
?>
Then here is my update updateform.php script:
<?php
include("dbinfo.php");
$sel_record = $_POST['sel_record'];
//$sel_record = (isset($_POST['sel_record'])) ? $_POST['sel_record'] : '';
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
//execute sql query and get result
$result = mysql_query($sql, $db) or die (mysql_error());
if (!$result) {
print "<h1> Something went wrong!</h1>";
} else
{ //begin while loop
while ($record = mysql_fetch_array($result, MYSQL_ASSOC)){
$id = $record["id"];
$type = $record['type'];
$depthead = $record['depthead'];
$person = $record["person"];
$descr = $record["descr"];
$recdate = $record["recdate"];
$tolog = $record["tolog"];
$senttorev = $record["senttorev"];
$recfromrev = $record["recfromrev"];
}
}
//end while loop
$pagetitle = "Edit Stat";
include ("header.php");
print <<<HERE
<h2> Modify this Stat</h2>
<p> Change the values in the boxes and click "Modify Record" button </p>
<form id="stat" method="POST" action="update.php">
<input type="hidden" name="id" value="$id">
<div>
<label for="type">Type*:</label>
<input type="text" name="type" id="type" value="$type">
</div>
<p>
</p>
<div>
<label for = "depthead" >Department Head*:</label>
<input type = "text" name = "depthead" id = "depthead" value = "$depthead">
</div>
<p>
</p>
<div>
<label for="person">Test Analyst*:</label>
<input type="text" name="person" id="person" value="$person">
</div>
<p>
</p>
<div>
<label for="descr">Description*:</label>
<input type="text" name="descr" id="descr" value="$descr">
</div>
<p>
</p>
<div>
<label for="recdate">Date Received*:</label>
<input type="text" name="recdate" id="recdate" value="$recdate">
</div>
<p>
</p>
<div>
<label for="tolog">Date to log*:</label>
<input type="text" name="tolog" id="tolog" value="$tolog">
</div>
<p>
</p>
<div>
<label for="senttorev">Sent to Rev:</label>
<input type="text" name="senttorev" id="senttorev" value="$senttorev">
</div>
<p>
</p>
<div>
<label for="recfromrev">Received from Rev*:</label>
<input type="text" name="recfromrev" id="recfromrev" value="$recfromrev">
</div>
<p>
</p>
<div id="mySubmit">
<input type="submit" name="submit" value="Modify Record">
</div>
</form>
HERE;
?>
And then the actual updating of the mysql has an update.php script:
<?php
include "dbinfo.php";
$id = $_POST['id'];
$type = $_POST['type'];
$depthead = $_POST['depthead'];
$person = $_POST['person'];
$descr=$_POST['descr'];
$recdate=$_POST['recdate'];
$tolog=$_POST['tolog'];
$senttorev=$_POST['senttorev'];
$recfromrev=$_POST['recfromrev'];
$sql="UPDATE stats SET
depthead='$depthead',
person='$person',
descr='$descr',
recdate='$recdate',
tolog='$tolog',
senttorev='$senttorev',
recfromrev='$recfromrev'
WHERE id='$id'";
$result=mysql_query($sql) or die (mysql_error());
print "<html><head><title>Update Results</titlel></head><body>";
include "header.php";
print <<<HERE
<h1>The new Record looks like this: </h1>
<td>
<p><strong>Type: </strong>$type</p>
<p><strong>Department Head: </strong>$depthead</p>
<p><strong>Test Analyst: </strong> $person</p>
<p><strong>Description: </strong>$descr</p>
<p><strong>Received Date:</strong>$recdate</p>
<p><strong>Date to Log:</strong>$tolog</p>
<p><strong>Sent to rev:</strong>$senttorev</p>
<p><strong>Received from Rev:</strong>$recfromrev</p>
<br/>
HERE;
Can someone please tell me why only one of the records keeps appearing doesn't matter which one I select from my index.php page. For some reason I think it is my $sel_record variable, but I am not sure and have run out of Ideas..
Thank you in advance..
Here's your issue in updateform.php:
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
That should be:
$sql = "SELECT * FROM stats WHERE id = $sel_record";
You missed out the $ symbol to call a variable, and you don't need quotation marks around an ID.

Categories