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.
Related
I'm trying to get all the rows which contain a particular text. However, when I execute the query, no rows are returned. I'm retrieving the text from a post request which looks like this "Krachttraining,Spinning" (= 2 values). I think my code fails on the following part (if I leave this out, the query returns some rows): AND CONCAT('%', sport.name, '%') LIKE $sports.
FYI. I know you can perform SQL injection on this, this will be fixed later.
<?php
$servername = "SECRET";
$username = "SECRET";
$dbpassword = "SECRET";
$dbname = "SECRET";
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sports = $_POST['sports'];
echo $sports; //Echo's: Krachttraining,Spinning.
// Create connection.
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND CONCAT('%', sport.name, '%') LIKE $sports";
$result = $conn->query($sql);
$output = array();
if ($result->num_rows > 0) {
// output data of each row.
while($row = $result->fetch_assoc()) {
$id = $row["id"];
array_push($output, $gym);
}
//Brackets because of GSON's parser.
echo "[" . json_encode($output) . "]";
}
$conn->close();
?>
EDIT: Changed SQL statement to:
$sql = "SELECT * FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports."%'";
Still getting 0 rows returned.
EDIT 2: I ran the following code in my phpMyAdmin environment, and it returned 0 rows.
Select * FROM sport WHERE name LIKE '%Krachttraining,Spinning%';
However when I'm running the following code, it returns 1 row:
Select * FROM sport WHERE name LIKE '%Krachttraining%';
I don't really get it what I'm doing wrong, any thoughts?
I think you want to use the IN statement.
This will check if any word in the array matches. For instance:
Select * FROM sport WHERE name IN ('Spinning', 'Krachttraining'); Will return every row which has the name Spinning or Krachttraining.
Just use:
SELECT .FROM...WHERE AND sport.name LIKE '%".$sports."%'";
After question editing
After you changed the question, I suggest to take a look at this answer to better understand what you should to do: https://stackoverflow.com/a/3902567/1076753
Anyway I think that you have to learn a bit about the like command: http://www.mysqltutorial.org/mysql-like/
Change the sql to :
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports%."'";
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 . ""
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%'");
The following code is a basic search engine of my database. The user enters a description and it returns a pupil id, pupil forename and surname accordingly. I know wish to make the value of '$id' (which represents a pupil id) a link/button that when clicked will retrieve from the database more specific information about the projects that individual pupil has completed.
Thank you for your time. Any help will be greatly appreciated.
{if(isset ($_POST ['search'])){
$searchq = $_POST['search'];
$searchq= preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM pupil WHERE pupil_forename LIKE '%$searchq%' OR pupil_surname LIKE '%$searchq%' OR pupil_id LIKE '%$searchq'") or die("Could not search");
$count = mysql_num_rows($query);
if ($count == 0 ) {
$output = "No Pupils fit that description. Try again or add new Pupil details <a href='pupilinput.php'>here.</a>";
} else{
while($row = mysql_fetch_array($query)){
$fname = $row['pupil_forename'];
$sname = $row['pupil_surname'];
$id = $row['pupil_id'];
$output .= '<div> <b>ID:</b> '.$id.' <b>Name:</b> '.$fname.' '.$sname.'</div><br>';
}
}
}}
I have a MySql DB and in the Table 'Klant' I have the column names:
ID
Naam
Email
Soort
Status
I get the column names with this query:
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
And I am selecting the data from the Table with this simple query:
$strSQL1 = "SELECT * FROM NAW.Klant";
What I want to do is search a text and with str_replace I want to replace the column_names with the data from the DB. For example:
If I type in Hello Naam, your email adress is Email I would want it to display Hello Robert your email adress is robert#gmail.com. And I will put that in a loop to do it for every row. I am currently using this:
$ID = $row['Klant_ID'];
$Naam = $row['Naam'];
$Email = $row['Email'];
$Soort = $row['Soort'];
$Naam = $row['Status'];
$vaaw = array("[ID]","[Naam]", "[Email]", "[Soort]", "[Status]");
$vervang = array("$ID","$Naam", "$Email", "$Soort", "$Status");
echo str_replace($vaaw, $vervang, $message);
The reason I do not want to use this anymore is because if I ever need to change/add/delete a column the code would still work. (I know it is a bad idea to change columns but you never know.) And also this code will work with other Tables/DB's to.
I have tried loads of things to get this to work but I just haven't got a clue how to do this and it has been bugging me for almost 2 days now. If someone knows a function or a way to do this it would be very helpful!
Try this:
<?php
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
$con=mysqli_connect('host', 'username', 'password', 'db');
if(!$con){
//error
}
$result=mysqli_query($con,$strSQL);
if(!$result){
//error
}
$table_columns=array();
//$row=mysqli_fetch_assoc($result);
while($row=mysqli_fetch_assoc($result))
{
$table_columns[]=$row['column_name'];
}
$query="select * from NAW.Klant "; //limit 10";
$result=mysqli_query($con,$query);
if(!$result){
//error
}
$greeting_text="";
while($row=mysqli_fetch_assoc($result)){
$greeting_text.= (isset($row['naam']))? "Hello {$row['naam']}":""; // because you want the 'hello'
for($i=1;$i< count($table_columns);$i++){
$greeting_text.=" Your ".$table_columns[$i]." is ".$row[$table_columns[$i]].", ";
}
$greeting_text.="\n";
}
echo $greeting_text; //test your result
If you have a predefined string template (to be replaced by column names or their values), you need to change that code when there is any change in the table columns. I simply choose to dynamically generate the string depending on the availability of columns. But if you need to use a predefined string, it is not difficult to do so.
I solved it using the script that HamZa linked in the comments. Since he is not posting it as an answer I will do it myself because I think it could help others.
The code that solved the problem is this:
$connection = mysql_connect('localhost', 'root', 'pw') or die('couldn\'t connect to the database.<br>'. mysql_error());
mysql_select_db("NAW");
$strSQL1 = "SELECT * FROM Klant";
$result = mysql_query($strSQL1, $connection) or die('Something went wrong with the query.<br>'. mysql_error());
while($row = mysql_fetch_assoc($result)){
$text = $_POST['naam'];
foreach($row as $k => $v){
$text = str_replace('['.$k.']', $v, $text);
}
echo $text;
echo "<br>";
}