Linking to search results directly - php

I got myself into a project at work that is going beyond my (very modest) coding skills.
So i have a database with 6 fields. I'm able to make searchs on it using php (i followed a youtube tutorial), add records, delete records and update records. All of that is working just fine.
What i need now is this:
I need to link search results (only a few, the most popular) on a image.
Per example, i have a company logo on my main page (let's say company name is..i dunno.. "Google". When i click on it, i wanted it to redirect to the search results of "google", like if i had inserted that in the search field. Is that possible?
(notice that i don't have companies in my database, i'm just trying to give an example so that people can understand what i intend. In my database i would need to link to reflect search results of the field "unidade")
Here is my code so far. The add / update .php i don't think are needed.
<?php
// include the connection file
include "connection.php";
$sql = "SELECT * FROM usuariotb";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .=" WHERE nome LIKE '%".$search_term."%'";
$sql .=" OR posto = '{$search_term}' ";
$sql .=" OR nim = '{$search_term}' ";
$sql .=" OR unidade LIKE '%".$search_term."%'";
$sql .=" OR codigoueo LIKE '%".$search_term."%'";
}
$query = mysql_query($sql) or die (mysql_error());
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM usuariotb WHERE id = {$id}";
mysql_query($sql_delete) or die(mysql_error());
header("location:display_data.php");
exit();
}
?>
<html>
<head>
<meta charset="iso-8859-1">
<title></title>
<link rel="stylesheet" type="text/css" href="format.css" />
</head>
<body>
<div class="container">
<form name="search_form" method="POST" action="display_data.php">
Search: <input type="text" name="search_box" value=""/>
<input type="submit" name="search" value="Procurar">
</form>
<div class="container">
<div class="content">
<div class="toolbar">Adicionar Novo Militar</div>
</div>
<div class="toolbar">Voltar à página de pesquisa</div>
</div>
</div>
<div class="container">
<div class="content">
<table width="90%" cellpadding="5" cellspacing="5">
<tr>
<td><strong>Nome</strong></td>
<td><strong>Nim</strong></td>
<td><strong>Posto</strong></td>
<td><strong>Unidade</strong></td>
<td><strong>Sigla Unidade</strong></td>
<td><strong>Observações</strong></td>
<td><strong>Acções</strong></td>
</tr>
<?php if (mysql_num_rows($query)) { ?>
<?php while ($row=mysql_fetch_array($query)) {?>
<tr>
<td><?php echo $row['nome'];?></td>
<td><?php echo $row['nim'];?></td>
<td><?php echo $row['posto'];?></td>
<td><?php echo $row['unidade'];?></td>
<td><?php echo $row['codigoueo'];?></td>
<td><?php echo $row['observacoes'];?></td>
<td>Delete</td>
<td>Edit</td>
</tr>
<?php } /* end loop */ ?>
<?php } else { ?>
<h2> Nothing to display!</h2>
<?php } /* end rows checking */ ?>
</table>
</div>
</div>
</body>
</html>

First of all, I empathize with you regarding being tasked with a more complex task than your current ability. Been there, done that. Many companies do this.
Regarding your task, for search every website usually uses GET to do the search e.g. https://www.google.co.in/search?q=stackoverflow. Notice the q=stackoverflow part. For this you do not need to submit any form, just use the URL directly.
So, I suggest you visit the websites where you want to link directly for search. Search for some sample text, say TEST and observe the URL of the page that opens.
Then using JavaScript/jQuery/etc, on click of the logo, read whatever text you want to search, create a URL in JavaScript and redirect there.
This is the general idea, feel free to comment and ask if you face any issues in implementation.

Related

PHP: Trying to Filter Database information in a table using a combo-box [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I am trying to sort information based the selected item in the combo box. I am familiar with parts of PHP but still learning.
I was able to fill the combo box with the 'Brand_Name' Column information from my DB.
This is my current output:
It is not filtering though, it is just listing all items in the DB
See code below:
<?php
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "Clients";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$queryDropdown = "SELECT * FROM `Brands` WHERE 1";
$result = mysqli_query($connect, $queryDropdown);
$queryGrid = "SELECT * FROM `Brands` ";
$SearchResult = mysqli_query($connect, $queryGrid);
?>
<html>
<head>
<title>PokerPass</title>
<link rel="stylesheet" type="text/css" href="styles/Main.css">
<link rel="stylesheet" type="text/css" href="styles/ComboBox.css">
<link rel="stylesheet" type="text/css" href="styles/TableGrid.css">
</head>
<body >
<div id="Container" class="Container">
<div id="Header" class="Header">
</div>
<div id="Body" class="Body">
<div name="start" id="Filter_Bar" class="Filter_Bar">
<select class="soflow" id="soflow" Size="1">
<?php while($row1 = mysqli_fetch_array($result)):; ?>
<option><?php echo $row1[1]; ?></option>
<?php endwhile; ?>
</select>
<button class="Submit" ><span><strong>Search<strong></span></button>
<!--<input class="Submit" type="submit" name="search" value="Search </span>">-->
</div>
<div id="Data_Grid" class="Data_Grid">
<table>
<tr>
<th>Server ID</th>
<th>Client</th>
<th>Operator</th>
<th>Username</th>
<th>Password</th>
</tr>
<?php while ($row = mysqli_fetch_array($SearchResult)):; ?>
<tr>
<td><?php echo $row['ServerID']; ?></td>
<td><?php echo $row['Brand_Name']; ?></td>
<td><?php echo $row['Operator_Name']; ?></td>
<td><?php echo $row['Username']; ?></td>
<td><?php echo $row['Password']; ?></td>
</tr>
<?php endwhile; ?>
</table>
</div>
</div>
<div id="Footer" class="Footer">
</div>
</div>
</body>
</html>
In your HTML code, your select element has no name attribute, so you won't be able to pick up its value when the form is submitted. Additionally, your option elements have no value attribute so even if the form was submitted and the select had a name, the value would be empty. See this guide.
Your select element isn't inside a form tag, which means that the page has no idea where to go when the button is pressed. You need a form that specifies the action (the URL you are going to) and the method (post/get). See this guide.
Finally, if you want PHP to know what your query was, you need to get it from the GET or POST parameters. Once you have the variable, you can make your SQL query dynamic - but be careful not to introduce an SQL injection vulnerability - validate the user input carefully (for instance, only allowing numbers as values in your select list) and/or use parameterized queries.
If you want the form to be submitted automatically when the dropdown list is changed, you can use a quick JS attribute to auto-submit the form.
You need to apply the filter value to your query, for your example
you need to construct a new query depending on your selection.
"SELECT * FROM Brands WHERE Client=" + $selectedClient;
Edit:
Here's a reference on how to pass a js variable to php:
How to pass JavaScript variables to PHP?

$_GET does not work and query the property

I have a problem with $_GET method. I have retrieved some data about admins of a webpage from database & I added a hyperlink for users to get the information about that them.
Here's the code in my 1st page:
<?php if(($adminlevel)==1){
echo '
<h4 class="widgettitle">List of admins</h4>
<table class="table responsive">
<thead>
<tr>
<th>Admin Level</th>
</tr>
</thead>
'; getAdmins(); echo '
</table>
';
}else{
echo '<h4 class="widgettitle">You dont have permission to see this table</h4>';
}
?>
<div class="divider15"></div>
The function getAdmins() goes like this:
<?php
function getAdmins(){
global $con;
$get_admin = "select * from admins order by id";
$run_admin = mysqli_query($con,$get_admin);
while($row_admin = mysqli_fetch_array($run_admin)){
$id_admin = $row_admin['id'];
echo "
<tbody>
<tr>
<td>Trident</td>
<td class='center'><a href='editlevel.php?id=$id_admin' title='Clik to change admin level' target='_blank'>$adminlevel_admin</a></td>
</tr>
</tbody>
";
}
}
?>
As you see I link the users from my first page to another page which is called editlevel.php by the function getAdmins().
Therefore I made my hyperlink like this:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
And Here's the editlevel.php page:
<body>
<?php
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
$get_result = "select * from admins where id='$result_id'";
$run_result = mysqli_query($con,$get_result);
while($row_result= mysqli_fetch_array($run_result)){
$id_target = $row_result['id'];
$username_target = $row_result['username'];
$adminlevel_target = $row_result['adminlevel'];
$email_target = $row_result['email'];
echo '
<div class="mainwrapper">
<div class="header">
'; include "php/php_includes/overall/header.inc.php"; echo'
</div>
<div class="leftpanel">
';include "php/php_includes/overall/leftpanel.inc.php"; echo '
</div><!-- leftpanel -->
<div class="rightpanel">
'; include "php/php_includes/gadgets/rightpanel.editlevel.php"; echo '
</div><!--rightpanel-->
</div><!--mainwrapper-->
';
}
}
?>
</body>
So basically I used if (isset($_GET['id_admin'])){ to get the results of the item which user clicked & try to retrieve the data of that item from database via that.. But the problem is nothing appears at my screen. No error message & no result. Please if you know how can I solve it please let me know!
It appears that your link is:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
When it should be:
<a href='editlevel.php?id_admin=$id_admin'>$adminlevel_admin</a>
In order for it to work with:
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
Edit: It goes without saying, you should never trust user input (such as $_GET). These values should be validated and sanitised before being used in SQL queries.

Can't output relevant mysql information to clicked link using SELECT *FROM table WHERE variable LIKE '$variable'

I have a mysql database named "drinks", in that database I have one table named "persons" and in "persons" I have two people, Bryan(fname) Fajardo(lname) 21(age) and Andross H Age:20.
In my index.php I have links set up from all of the people in table persons.
I am trying to get my links to work so that when I click on either name, the information relevant from that person is outputted into my other page (where the link goes to) which is: insert.php.
I have been trying for hours to run some test by clicking on the Bryan link and outputting only his last name etc. etc. My objective: is to be able to link the people from "persons" table and then upon click go to insert.php and output that person's information there.
Here is my current code from Index.php.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Connect to the database
$con = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">MSQL Connected.</span>' ;
}
$result = mysqli_query($con,"SELECT * FROM persons");
while($row = mysqli_fetch_array($result)) {
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
}
mysql_close();
?>
</body>
</html>
and here is my Insert .php where I want the relevant information to be printed.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class = "full-header">
<div class = "mid-header span12 center">
</div>
</div>
<div class = "main-content-container full_w">
<div class = "span12 main-content center">
<?php
$cont = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">yay</span>' ;
}
$fname = $_GET['fname'];
$sel = ($cont,"SELECT * FROM persons WHERE fname ='%$fname%'");
while($rower = mysqli_fetch_array($sel)) {
Print $rower['lname'];
//why is this not printing Bryan's last name?
}
?>
</div>
</div>
</body>
</html>
Thank you in advance, I appreciate the help, I have just recently gotten into php and database building/summoning.
EDIT: I also have been reading that this is becoming deprecated and PDO is going to be used now, if you have a solution that involves PDO, I would appreciate that as well, but I am very new to PDO.
EDIT 2: Changed "table" to "persons" in insert.php query.Still did not fix.
I can understand how it is when first starting out. Once you wrap your mind around the basic parts of it the rest will flow.
Since you asked for a better way I am going to suggest a class I personally use in all my projects.
https://github.com/joshcam/PHP-MySQLi-Database-Class
Of course don't forget to download the simple MYSQLI class from the link above and include it just like I do below in your project. Otherwise none of this will work.
Here us the first page which contains the table with all the users from your persons Db table. We list them in a table with a simple edit/view button.
PAGE 1
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all users in the DB table persons
$users = $db->get('persons'); //contains an Array of all users
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th> </th>
<?php
//loops through each user in the persons DB table
//the id in the third <td> assumes you use id as the primary field of this DB table persons
foreach ($users as $user){ ?>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<a href="insert.php?id=<?php echo $user['id']; ?>"/>Edit/View</a>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
So that ends your first page. Now you need to include this code on your second page which we are assuming is called insert.php.
PAGE 2
<!--add this to your insert page-->
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all the user where the GET
//variable equals their ID in the persons table
//(the GET is the ?id=xxxx in the url link clicked)
$db->where ("id", $_GET['id']);
$user = $db->getOne('persons'); //contains an Array of the user
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>user ID</th>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<?php echo $user['id']; ?>
</td>
</tr>
</body>
</html>
You have two main errors. On index.php you are wrapping your query string values in quotes
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
This should really be
Print '<dd><a href="insert.php?
fname='.$row['fname'].'">'.$row['fname'].'</a></dd>';
Next, on your second page, you need to use LIKE on your query.
$sel = ($cont,"SELECT * FROM persons WHERE fname LIKE '%$fname%'");
That said, you really should use parameters because the current method is going to open your script up to SQL Injection, and you should consider using a primary key in your querystring instead of passing the person's name.
Print '<dd><a href="insert.php?
id='.$row['id'].'">'.$row['fname'].'</a></dd>';
And your query
$id = intval($_GET['id']);
$sel = ($cont,"SELECT * FROM persons WHERE id = $id");
One final note, on your index page, you are using mysql_close instead of mysqli_close to close your database connection.

How do i access a php file in a search query?

Ok, so I'm making a somewhat simple search feature that connects to a MySQL server.
From my understanding the way to do this is to:
Make a search page on the site.
The search page will then accept a query and run it in the .php you provide
A result page will come out.
This is the basic stock code i will use:
<html>
<body>
<form action="searchtemplate.php" method="post">
Part ID: <input type="text" name="partID" />
<input type="submit" /></form>
</body>
</html>
I got this from the w3 school site.. it's simple and it works.
The php file i'm using is:
<?php
/**
Template Name: My Template
*/
get_header(); ?>
<div class="clearfix left-sidebar">
<!--BEGIN #primary-->
<div id="primary">
<?php the_post(); ?>
<?php $con=mysqli_connect("server","user","pass","database");
// Check connection
if (mysqli_connect_errno())
{
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$part_query = $_POST['partID'];
$result = mysqli_query($con,"SELECT * FROM Parts WHERE part_id = $part_query");
echo "<table border='1'>
<tr>
<th>part_id</th>
then rest of columns
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['part_id'] . "</td>";
then echo rest of columns
echo "</tr>";
}
echo "</table>";
mysqli_close($con); ?>
<!--END #primary-->
</div>
<?php get_sidebar(); ?>
</div>
<?php get_footer();
?>
Ok, so I am using wordpress and I set this php up in the main theme directory and it can be accessed as a template. My main problem is that the search page appears fine but when I click submit it takes me to a blank page and not to the result page. I'd like to know if this is the correct way of doing what i am trying to accomplish or if there is a better way.
Your form is likely posting to the template, searchtemplate.php, and not a Wordpress page using the template to execute the code.
<form action="searchtemplate.php" method="post">
The "action" parameter in your form tag should point to the actual page on your site that is using your custom template.

PHP Combining search function with pagination

So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.

Categories