I am currently working on a project in grad school. I am constructing a database that is writeable as well as searchable. I have completed the writeable aspect, however I am having issues with the search function. THe issue is I am unable to search and display an individual row in the database, only the entire database, which lets be honest, not very functional if a database has 20k items and you only need 20.
I am copying the code in its entirety below.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_NOTICE);
// --------------------------------------------------------
/* THIS DEMO FILE ACCEPTS DATA FROM A WEB FORM
AND SAVES THE DATA TO A FLAT FILE AND THEN TO A DATABASE.
AS A CHECK WE READ THE DATA BACK FROM THE TABLE AND FROM
THE FILE.
Created by: PATRICK DUFF, based on example written by G. Benoit, on 2/28/15
Modified on: 3/1/15, 3/5/15/ 3/13/15
Contact: xxxxxxx
*/
// --------------------------------------------------------
/* GETTING READY FOR THE DATA */
/* the file to hold the data */
$filename = "testData.txt";
$status = "";
/* name of the database, table, username, password, table */
$hostname = "xxxxxxx"; // change this vars for your own db
$username = "xxxxx"; // whatever your student email user name is
$password = "xxxxx"; // your usual password
$dbname = "xxxxxx"; // this database name is assigned for you by the Lab Staff Lab Staff
$table = "xxxxxx"; // once you’re using your DB, you can create your own tables
//getting data from webfrom
$isbn = $_POST["isbn"];
$lname = $_POST["lname"];
$fname = $_POST["fname"];
$title = $_POST["title"];
$publisher = $_POST["publisher"];
$genre = $_POST["genre"];
$con = mysqli_connect("$hostname", "$username", "$password", "$dbname");
$isbn = $_POST["isbn"];
$lname = $_POST["lname"];
$fname = $_POST["fname"];
$title = $_POST["title"];
$publisher = $_POST["publisher"];
$genre = $_POST["genre"];
$con = mysqli_connect("$hostname", "$username", "$password", "$dbname");
//retrieving data from flat form & database.
echo "<!DOCTYPE html><html><head> <title> Record Search </title></head>";
echo "<body> Here is the data: The file contents of 'testData.txt so far is/are: ";
echo file_get_contents($filename);
echo "<hr /> End of reading file. Attempting to read database <hr />";
//creating searchability
$sql= "SELECT * FROM myLibrary WHERE isbn LIKE '%" .$isbn." %' OR fname LIKE '%" .$fname." %' OR lname LIKE'%" .$lname." %' OR title LIKE '%" .$title." %' OR publisher LIKE '%" .$publisher." %' OR genre LIKE'%" .$genre."%' ORDER BY lname" or
die(mysql_error());
$result = mysqli_query($con, $sql);
//displays result in table
if ($result->num_rows > 0) {
echo "<table id='myLibrary'><tr><th><u>ISBN</u></th><th> <u>First Name</u></th><th><u> Last Name </u></th><th><u> Title</u> </th><th><u>Publisher</u></th> <th><u>Genre</u></th></tr>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row["isbn"]."</td><td>". $row["fname"]."</td><td>" . $row["lname"]. "</td><td>" .$row["title"]. "</td><td>" .$row["publisher"]. "</td><td>".$row["genre"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
echo "End of Results";
For some reason when I comment out the table, nothing from the table gets displayed.
I hope this was clear enough, it's my first time posting here.
You only need to limit the query to avoid returning all the results.
$limit = 10;
$sql= "SELECT * FROM myLibrary WHERE isbn LIKE '%" .$isbn." %' OR fname LIKE '%" .$fname." %' OR lname LIKE'%" .$lname." %' OR title LIKE '%" .$title." %' OR publisher LIKE '%" .$publisher." %' OR genre LIKE'%" .$genre."%' ORDER BY lname LIMIT " .$limit . ""
Related
my project partner and I are relatively new to PHP and needed some help in searching through multiple columns. We are trying to have a functioning search bar that returns the name and corresponding youtube url of a comedian depending on the first and last name that was searched. We got it to work with first name OR last name being searched but not with both of them. (i.e Sarah or Silverman will work but not Sarah Silverman) We tried changing the clause to AND but that did not work at all. Below is our search code.
The line
$searchdb = mysqli_query($con,"SELECT *
FROM comedian
WHERE fname LIKE '%$searchq%'
OR lname LIKE '%$searchq%'")
or die ("Could not search.");
is what we are trying to modify.Thank you!
<?php
session_start();
$con = mysqli_connect('localhost','root','') or die("Could not connect");
mysqli_select_db($con, 'youtube') or die(mysqli_error($con));
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
//Will replace everything that is not a letter or number with blank.
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$searchdb = mysqli_query($con,"SELECT *
FROM comedian
WHERE fname LIKE '%$searchq%'
OR lname LIKE '%$searchq%'")
or die ("Could not search.");
$count = mysqli_num_rows($searchdb);
if($count == 0){
$output = 'There were no search results.';
print("$output");
}else{
while($row = mysqli_fetch_array($searchdb)){
//Variables
$fname = $row['fname'];
$lname = $row['lname'];
$comedianid = $row['comedianid'];
//Output first and last name
$output .= '<div> <b>Comedian:</b> '.$fname.' '.$lname.'</div>';
//Matching comedian with respective video URL using about table relation.
$searchdb2 = mysqli_query($con,"SELECT * FROM about WHERE comedianid LIKE '%$comedianid%'") or die ("Could not find a video by this author.");
//Fetches comedian id from about table
$row2 = mysqli_fetch_array($searchdb2);
$url = $row2['url'];
$outputvid = preg_replace("#.*youtube\.com/watch\?v=#","",$url);
$outputvid = '<iframe width="700" height="600" src="https://www.youtube.com/embed/'.$outputvid.'"></iframe>';
print("$output");
print("$outputvid");
$output = '';
}
}
}
You can concatenate the first and last name and then search based on that string...
SELECT *
FROM comedian
WHERE fname || ' ' || lname LIKE '%Sarah Silverman%'
This will show "Sarah Silverman", even though Sarah is stored in fname and Silverman in lname
Edit: I have tested it in SQLite, you might have to change || to + based on your database management system.
I am having an issue where I can not search for the exact data I want.
I can search the database fine and return all the values in the format I want. However i want to add in the ability to search by a company's name and also display those results in the same table. The companys Names are not stored in the databse but are in the Array session pulled from an API. We store the ID for each company in the database which is set as the Keys from the array.
I want to know if there is any way to get results given form the array as well as the database search.
I know i can do it with a foreach loop around all my SQL SELECT Statement, but the issue with that is if there is no match in the array it will not run any search, making the rest of the search very limited as searching by IP Address is one of the main reasons for this. the only way I think it is possible is adding a foreach loop into the SQL statement but I don't see how that is possible nor can i find any documentation on it online. please help!
Here is my code that runs based on an input from a search box sent by AJAX.
// Start sessions, Connected to DB set customer array
session_start();
$conn = connect();
$customers = $_SESSION['array'];
// if ajax posted search input
if($_POST){
$search = mysqli_real_escape_string($conn, $_POST['search']);
//set a second input for checking against customers array and format to give results
$input = $search
$input = strtolower($input);
$input = "'$input'";
$result = preg_grep($input, $customers);
$arrayk = array_keys($result);
//SELECT Search mysql Query
$matchingcompanies = "";
foreach($arrayk as $id)
{
$matchingcompanies .= "'" . $id . "' OR ";
}
$matchingcompanies = substr($matchingcompanies,0,strlen($matchingcompanies)-4);
$query1 = "SELECT * FROM IPV4_linked WHERE `companyId` = (" . $matchingcompanies . ") OR concat(ipv4Address, ipv4Subnet, hostName, owner, siteName) like '%" . $search . "%'";
$view4 = mysqli_query($conn, $query1);
//Table Title row
echo "<div><table name ='ipv4' class='tableparent'><td class='tabled'>IP Address</td><td class='table'>Subnet</td><td class='table'>PC Name</td><td class='table'>Owner</td><td class='table'>Customer</td><td class='table'>Customer Site</td></tr>";
//loops through search results and echo table
while ($row = mysqli_fetch_array($view4)){
$id = $row['companyId'];
$company = $customers[$id];
echo "<tr><td class='tabled'>". $row['ipv4Address']."</td><td class='table'>". $row['ipv4Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>".$company."</td><td class='table'>".$row['siteName']."</td></tr>";
}
echo"</table></div>";
}
?>
Solved the issue by adding in a matchingcompanies field before and setting it to an exceeding long string with lots of OR's, i will limit the search to only start after 3 characters inputed so the string return is not so large.
//SELECT Search mysql Query
$matchingcompanies = "";
foreach($arrayk as $id)
{
$matchingcompanies .= "'" . $id . "' OR ";
}
$matchingcompanies = substr($matchingcompanies,0,strlen($matchingcompanies)-4);
$query1 = "SELECT * FROM IPV4_linked WHERE `companyId` = (" . $matchingcompanies . ") OR concat(ipv4Address, ipv4Subnet, hostName, owner, siteName) like '%" . $search . "%'";
$view4 = mysqli_query($conn, $query1);
hi i am new to php mysql. I have created a form where the user can search the database, and the result depends on how the user fills in the form. form has 6 search fields. where user can choose / fill any of one or more fields to make his search. i have coded it as follows
php
<?php require_once('Connections/osrc.php'); ?>
<?php
$maxRows_search_result = 10;
$pageNum_search_result = 0;
if (isset($_GET['pageNum_search_result'])) {
$pageNum_search_result = $_GET['pageNum_search_result'];
}
$startRow_search_result = $pageNum_search_result * $maxRows_search_result;
mysql_select_db($database_osrc, $osrc);
$propertyid = $_POST['propertyid'];
$offered = $_POST['offered'];
$property_type = $_POST['property_type'];
$beds = $_POST['beds'];
$city = $_POST['city'];
$locality = $_POST['locality'];
$query_search_result = "SELECT * FROM osrc_data WHERE propertyid LIKE '%$propertyid%' OR offered LIKE '%$offered%' AND property_type LIKE '%$property_type%' AND beds LIKE '%$beds%' AND city LIKE '%$city%' AND locality LIKE '%$locality%' ";
$query_limit_search_result = sprintf("%s LIMIT %d, %d", $query_search_result, $startRow_search_result, $maxRows_search_result);
$search_result = mysql_query($query_limit_search_result, $osrc) or die(mysql_error());
$row_search_result = mysql_fetch_assoc($search_result);
if (isset($_GET['totalRows_search_result'])) {
$totalRows_search_result = $_GET['totalRows_search_result'];
} else {
$all_search_result = mysql_query($query_search_result);
$totalRows_search_result = mysql_num_rows($all_search_result);
}
$totalPages_search_result = ceil($totalRows_search_result/$maxRows_search_result)-1;
?>
now when user It works but it shows all rows in database table.
for example user fills up three fields beds, city, locality and rest of three are blank.
search result page shows all rows in data base with all records.
pls help me to correct my codes. Thanks in advance
First, I agree with #VaaChar, you should be using mysqli or even better yet PDO.
You will have determine IF a value has been placed in a field and if so use it in your query. If no value was placed in the field ignore it in your query.
Something like this...
$sqlid = "";
$sqloffered = "";
$sqltype = "";
$sqlbeds = "";
$sqlcity = "";
$sqllocality = "";
if(isset($propertyid)) {
$sqlid = " propertyid LIKE '%$propertyid%'";
}
if(isset($propertyid) && isset($offered)) {
$sqloffered = " OR offered LIKE '%$offered%'";
}
if(!isset($propertyid) && isset($offered)) {
$sqloffered = " offered LIKE '%$offered%'";
}
if(isset($property_type)) {
$sqltype = " AND property_type LIKE '%$property_type%'";
}
if(isset($beds)) {
$sqlbeds = " AND beds LIKE '%$beds%'";
}
if(isset($city)) {
$sqlcity = " AND city LIKE '%$city%'";
}
if(isset($locality)) {
$sqllocality = " AND locality LIKE '%$locality%'";
}
$sql = "SELECT * FROM osrc_data WHERE {$sqlid}{$sqloffered}{$sqltype}{$sqlbeds}{$sqlcity}{$sqllocality} ";
When you build the sql query with (say) $propertyid empty, you get this :
.... LIKE '%%' ...,
which is like saying "anything". You must build your query only with the fields that have been filled.
its my first post and I have a problem with a PHP search.
Here,
$searchq = $_POST['searchq'];
so far when a single word is supplied for searchq like naresh, google, lamgade then it search in a db but when there is a multiple search like
naresh lamgade at a same time then there is error for these word because it only search in a first_name column and what i want to search naresh in a first_name column and lamgade in a last_name column
Here is the code
<pre> $searchq = $_POST['searchq'];
$conn = mysqli_connect('localhost','root','','std_info') or die("Cant' Connect to db");
$query = mysqli_query($conn,"select * from student_details where first_name like '%$searchq%' or last_name like '%$searchq%'");
$count = mysqli_num_rows($query);
if($count == 0) {
echo "<br>";
echo "Can't find, try entering only first name or last name";
}
else {
do something`</pre>
}
The problem is
In a search bar, when i try entering naresh lamgade and search then
searchq =naresh+lamgade
and it search in both first_name and last_name column with a naresh+lamgade so there is no result.
I want to know , how to break these two words and search in a different column with these words.
The problem is
In a search bar, when i try entering naresh lamgade and search then
searchq =naresh+lamgade"
I guess that you put the textfield inside a form without method="post".
If you did, try like this in searchq:
... WHERE first_name LIKE "'%'.$searchq.'%'" or last_name like "'%'.$searchq.'%');
Use explode to split query.
Also your code is dangerous. Use mysqli_escape_real_string to escape special characters in a query:
<?php
$searchq = explode(" ", $_POST['searchq']);
$conn = mysqli_connect('localhost', 'root', '', 'std_info') or die("Cant' Connect to db");
$query = mysqli_query($conn, "select * from student_details where (first_name like '%" . mysqli_real_escape_string($searchq[0]) . "%' OR first_name like '%" . mysqli_real_escape_string($searchq[1]) . "%') OR (last_name like '%" . mysqli_real_escape_string($searchq[1]) . "%' OR last_name like '%" . mysqli_real_escape_string($searchq[0]) . "%'");
$count = mysqli_num_rows($query);
if ($count == 0)
{
echo "
";
echo "Can't find, try entering only first name or last name";
}
else
{
do something`
Thanks everyone for the answer but I have used this query and it's working perfectly as I wanted.
$query = mysqli_query($conn, "SELECT * FROM student_details WHERE CONCAT(first_name,' ',last_name) like '%$searchq%'");
i'd like to write a function which grabs all fields from a database table and puts it in an array.
getting the database fields already works like this:
$sq = "select column_name,data_type from information_schema.columns
where table_name='users'";
i'm just not sure how to store them properly.
when having eg. this database structure:
fieldname type length
--------------------------------
id int 11
username varchar 50
pass varchar 50
lastlogin date
what's the best way to store this data in php in order querying it like this:
$field = myFields["username"];
echo $field->id."/".$field->type."/".field->length;
as you can see i'd like to access the data directly by field name
Make sure you connect to the database first. Then do:
$r = mysql_query('SELECT COLUMN_NAME AS fieldname,
DATA_TYPE AS type,
CHARACTER_MAXIMUM_LENGTH AS length
FROM information_schema.columns
WHERE table_name = "users" AND column_name = "username"');
if ($r)
{
$field = mysql_fetch_object($r);
// $field->type, $field->length, etc.
}
$sql = "YOUR QUERY HERE";
$res = mysql_query($sql);
while ($rowobj = mysql_fetch_object($res)) {
// do what you want to do with $rowobj
echo $rowobj->column_name1 . "<br />\n";
echo $rowobj->column_name2 . "<br />\n";
// ...rest of code...
}
Put your query into $sql variable and replace column_nameX in while loop with columns you SELECTed with your query.
$query = mysql_query("SELECT * FROM table");
$result = array();
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
unset($row['username']);
$result[$username] = (object)$row;
}
Then you can access it by using:
$result['username']->id