Display result using IF/ELSE in PHP - php

I have a sample code for my problem. what i want to do is if i search for "Helloworld" then i want to inform the user that there's no data matched based from their inputted data. Im thinking if can i use if else statement to do a validation if the data inputted didn't matched any rows and if the inputted data matched some rows. As i visualized the solution for this problem i think this method is the solution but i don't how can i do this. i think the solution is to put if else condition here's my code how i thought about it
if the result of search is not nothing then it will show the result then if nothing then the message will appear "no data matched"
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<?php
if($result_validation != ''){
?>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
<?php
}else{
echo "no data matched";
}
?>
</form>
</body>
</html>

I see no point in displaying the entire table inside the form, you should display it somewhere outside of the form. Having said that, $result_validation variable is undefined, you need to use $search_result in your code.
And as per your question, use mysqli_result::$num_rows to check number of rows returned from the SELECT query.
if($search_result->num_rows){
// display table
}else{
echo 'no data matched';
}

Related

Php/SQL Table Search with Space

I setup a php file to pull data from a database, and list that on a table. I then made a simple search function to search that data, however I can't figure out how to implement a space when searching. For example, if I searched test 2 (test from one column, 2 from another) it won't display anything. However, if I were to search 'test2' or '2test' it displays all results. How would I implement that space into my code?
Here's my code:
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `master` WHERE CONCAT_WS(`id`, `office`, `firstName`, `lastName`, `type`, `status`, `deadline`, `contactPref`, `email`, `phoneNumber`, `taxPro`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `master`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "", "", "");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
echo "test";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="Untitled-1.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>ID</th>
<th>Office</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
<th>Status</th>
<th>Deadline</th>
<th>Contact Preference</th>
<th>Email</th>
<th>Phone Number</th>
<th>Tax Pro</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['office'];?></td>
<td><?php echo $row['firstName'];?></td>
<td><?php echo $row['lastName'];?></td>
<td><?php echo $row['type'];?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['deadline'];?></td>
<td><?php echo $row['contactPref'];?></td>
<td><?php echo $row['email'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
<td><?php echo $row['taxPro'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>```
A way to do this could be to have your string spillted up into words in php. You could use explode function for this (https://www.php.net/manual/en/function.explode.php)
And then write SQL where clause like this (im assuming you are using mysql):
WHERE col LIKE %word% OR col LIKE %word2%
This would be a bit inefficient, maybe the tool what you are looking for is elasticsearch? https://www.elastic.co/what-is/elasticsearch
Also, you should NEVER use . operator on an untrusted input. Because it creates MySQL Injection vulnerability. See this question for reference: How can I prevent SQL injection in PHP?
The simplest solution would be using FULLTEXT index in your mysql field. But I don't recommend using it on production. Instead, for actual projects external searching engine must be considered (e.g. Elasticsearch, etc.)

PHP website search

I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.

Can't search for a specific record in database

I want to search for a specific record in database and show it on html page. I have inserted a search bar with a search button. I want to enter let's say Student Name and view the record of that student in an html table. But it's not working, It shows nothing in the table. Here is the code for search:
<?php
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch=$_POST['valueToSearch'];
$query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%";
$search_result=filterTable($query);
}
else{
$query="SELECT * FROM 'table_name'";
$search_result=filterTable($query);
}
function filterTable($query)
{
$connect=#mysql_connect("localhost","root","","db");
$filter_Result=#mysql_query($connect,$query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Record</title>
<style>
table,tr,th,td
{
border:1px solid black;
}
</style>
</head>
<body>
<form action="search.php" method="post">
<input type="text" name="valueToSearch" placeholder="ValueToSearch"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Forget any mysql_ feature. You are establishing connection to database with mysql but trying to read results with mysqli_.. Try with
<?php
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch=$_POST['valueToSearch'];
$query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%'";
$search_result=filterTable($query);
}
else{
$query="SELECT * FROM 'table_name'";
$search_result=filterTable($query);
}
function filterTable($query) {
$connection = new mysqli("localhost", "root", "","db");
$filter_Result = $connection->query($query)
return !$filter_Result ? null : $filter_Result;
}
?>
Then, down in your form, replace:
while ($row = $search_result->fetch_array()) {
...
...
}
Hint:
Consider about moving your connection establishment from filterTable() function to the connection.php file and use GLOBAL $connection; in the function
Moving your connection to that file will allow you to escape string at any time with $myVar = $mysqli->real_escape_string( $myVar ) which will prevent injection
escape your keywords with mysql_escape_string();, like second thing don,t use mysql* use mysqli or pdo because mysql* has been removed from php 7.*
$valueToSearch= mysqli_real_escape_string($connect,$_POST['valueToSearch']);
after that use this query
$query="SELECT * FROM table_name WHERE Student_Name LIKE '%$valueToSearch%'";
because you have syntax error if you echo it you need to get like this
SELECT * FROM table_name WHERE Student_Name LIKE 'something';
i am giving you example with mysqli paste it in connection.php
$connect=mysqli_connect("localhost","root","","db");
now your code should be
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch= mysqli_real_escape_string($connect,$_POST['valueToSearch']);
$query="SELECT * FROM table_name WHERE Student_Name LIKE '%$valueToSearch%'";
$search_result=filterTable($query,$connect);
}
else{
$query="SELECT * FROM table_name";
$search_result=filterTable($query,$connect);
}
function filterTable($query,$connect)
{
$filter_Result=mysqli_query($connect,$query);
if (!$filter_Result) {
die('query is not valid '.mysqli_error($connect));
}
else{
return $filter_Result;
}
}

Pagination onOn search result with PHP only

I'm a PHP student and I'm developing my first app. I need to add pagination on the search results with this code below. I can't use datatables or another plug-ins because it's hard for me to put action buttons and my data on table.
If you know some simple method that can be not so hard to implement will help a lot.
I'm using the example from this dev: how to search and filter with php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Below example will work wells for requirements :
mysql_connect("localhost","wellho","wawawawa");
mysql_select_db("wellho");
$perpage = 10;
$html = "";
$startat = $_REQUEST[page] * $perpage;
$limlim = "%".$_REQUEST[look4]."%";
$q = mysql_query("select count(entry_id) from mt_entry where entry_title like '$limlim'");
$row = mysql_fetch_array($q);
$havesome = $row[0];
$pages = floor(($row[0]-1) / $perpage) +1 ;
$q = mysql_query("select * from mt_entry where entry_title like '$limlim' order by entry_id desc limit $startat,$perpage");
while ($row = mysql_fetch_assoc($q)) {
$text = strip_tags($row[entry_text]);
$text = substr($text,0,300);
$html .= "<dt>$row[entry_id] - <a href=/mouth/$row[entry_id]_.html target=pix>$row[entry_title]</a></dt>";
$html .= "<dd>$text ....<br><br></dd>";
};
$lynx = "Please choose the next page you want to view:";
for ($k=0; $k<$pages; $k++) {
if ($k != $_REQUEST[page]) {
$lynx .= " ".($k+1)."";
} else {
$lynx .= " <b>--".($k+1)."--</b>";
}
}
if ($pages < 2) {
$lynx = "All results shown on this page";
}
if ($havesome == 0) {
$lynx = "Sorry - no titles matched. Please change your search string";
}
?>
<html><head>
<title>Showing blog entries</title>
<body>
<h2>Search titles on "The Horse's Mouth"</h2>
<form>Search only for titles including ... <input name=look4
value="<?= htmlspecialchars(stripslashes($_REQUEST[look4])) ?>">
(Please leave box empty to select all titles)<br>
<input type=submit></form><br>
<h2>Here are the entries you selected - page <?= $_REQUEST[page]+1 ?>:</h2><br>
<?= $html ?>
<?= $lynx ?>
</body>
You should use limit and offset to paginate the results.
<?php
...
// If no 'page' parameter is found, default to 1
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
// Results per page
$limit = 10;
// Offset = (page - 1) * limit. (page 1 = 0, page 2 = 10, etc...)
$offset = ($currentPage - 1) * $limit;
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%' LIMIT $limit OFFSET $offset";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users` LIMIT $limit OFFSET $offset";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
Previous
Next
</body>
</html>
PS: In the previous example i didn't checked if the page is the first or last, you should do that.

How to retrieve data from two tables in a search function [duplicate]

This question already has answers here:
Mysql Query with two tables php
(4 answers)
Closed 5 years ago.
So I have this simple search code
<div id="page">
<!-- start content -->
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `pdspersonalinfo` WHERE CONCAT(`personid`, `surname`, `firstname`, `sex`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `pdspersonalinfo`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "ucwd");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="searchtrain[orig].php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search" autocomplete="off"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table bgcolor="#FFFFFF">
<tr>
<th>ID</th>
<th>Surame</th>
<th>First Name</th>
<th>Sex</th>
<th>Training</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['personid'];?></td>
<td><?php echo $row['surname'];?></td>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['sex'];?></td>
<td><?php echo $row['traintitle'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
</div>
But I want my search_results to retrieve data from two tables having a common column
My first table is named pdspersonlinfo and has the following rows personid, position, day, month, year, surname, firstname, middlename, sex
My second table is named pdstrain and has the following rows personid, trainid, traintitle, trainfrom, trainto
When I search, for example the name Jacob, the data surname,firstname middlename - traintitle will be retrieved
I'm very much a beginner on php and mysql. I hope this can be comprehended.
I thank you in advance ^_^
You can join the tables in your select query
SELECT
I.surname, I.firstname, I.middlename, P.traintitle
FROM pdspersonlinfo I
LEFT JOIN pdstrain P ON P.personid = I.personid
WHERE CONCAT(I.personid, I.surname, I.firstname, I.sex) LIKE '%valueToSearch%'
Don't forget to properly escape the user inputted search value!
You need a join.
SELECT a.something, b.something
FROM tableA a JOIN tableB b
ON a.id = b.id

Categories