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%'");
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 trying to make a search for my website where if i search with member certificate no it will show his full details. But in my code when i search for Certificate No : 1 it show details of Certificate no 1, 10, 11,12,13,14,15,....
Is there any way to show single member details.
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM certificate WHERE certificate_no LIKE '%$searchq%' ") or die ("could not search ");
}
$count = mysql_num_rows($query);
if($count==0){
$output = 'There is no search result ';
} else {
while ($row = mysql_fetch_array($query)){
$name =$row['name'];
$certificate_no =$row['certificate_no'];
$y_of_passing =$row['y_of _passing'];
$grade =$row['grade'];
$score =$row['score'];
$output.='<div>Certificate Number : ' .$certificate_no.' <div>Candidate Name : '.$name. '<div>Grade/Score : ' .$grade.' <div>Course Name : '.$score. '<div>Year Of Passing: '.$y_of_passing.'<div>';
echo "<img src ='".$row['photo']."' height='100' width='200' >" ;
}
}
print("$output");
Change your query:
$query = mysql_query("SELECT * FROM certificate WHERE certificate_no LIKE '%$searchq%' ")
to
$query = mysql_query("SELECT * FROM certificate WHERE certificate_no = ". $searchq ."
and try again.
Explanation: When you are using LIKE '%$searchq%' then it will search for a string having 1 at any place i.e. PATTERN MATCHING. But If you want equality comparison than try =. It will search for exact match.
You're using wrong wildcards Use either = or only like or use RLike
SELECT * FROM certificate WHERE certificate_no LIKE '$searchq'
SELECT * FROM certificate WHERE certificate_no = '$searchq'
SELECT * FROM certificate WHERE certificate_no RLike '[[:<:]]$searchq[[:>:]]'
Try editing the $query like this :::
$query = mysql_query("SELECT * FROM certificate WHERE certificate_no LIKE $searchq ") or die ("could not search ");
Like is a pattern matching . It will search the given string in your column.That's why it's returning matched pattern result like this 10, 11,12,13,14,15 .Did you notice that the result all have that 1 . which is you used to match the pattern in like '%1%' . so you need to use comparison operator like this certificate_no=1
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
On my site, I have 4 radio selectors to add a filter to my search script. If a filter is selected, it should run the search script on only the column which the filter is set to, otherwise if the filter is set to all or not set, it should search all columns. However, when I set my filter to search only one column (the all option works), the query returns an empty result. I have tested the query and it works fine.
I have posted the code for the whole script, however the code block in question is marked with comments. The $filter and $search variables both come through correctly. I have tested this from within the script.
<?php
include ('connect.php');
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(isset($_POST['filter'])) {
$filter = $_POST['filter'];
if($_POST['filter'] == "all") {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
else {
//Code block in question starts
echo "Searching filtered selection only";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
//Code block in question ends
}
}
else {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
}
else {
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes");
}
while ($row = mysqli_fetch_array($query)) {
echo "<div class='crane'><a href='#!edit' id='" . $row['id'] . "'><img src='images/" . $row['image'] . "' /><p class='craneName'>" . $row['brand'] . ' ' . $row['model'] . "</p></a></div>";
}
?>
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes
WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
You’ve put the column name you are passing in $filter in single quotes here, which makes it a mere text literal instead of a column name.
So remove the single quotes … and after that, go read up on SQL injection, but quickly.
I have this query
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
I need it to do so that the scrip dies if it gets a result, right now i have this :
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
if($DB->record_count() != 0) {
Should this be something els? Because it dosnt die, even though i KNOW its got a result
This query looks like this in the phpscript. Its part of a bigger site
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
$Properties['Title'] = String from the upload script that contains the titel.
$DB is the call til mysql
filter = the row in mysql
tfilter = the database name
WHAT DO I NEED:
I need the php to search the the tabel TFILTER in the row FILTER for matches to $Properties['Title'] and if it finds any then DIE. If the string: The.White.Tiger. exist in FILTER row, og the $Properties['Title'] contains The.White.Tiger.In.The.Yard, the the php should DIE.
I think your query needs to be (repace the single quotes around $Properties['Title'] with backtick):
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE CONCAT('%', filter, '%')");
Also, you don't need to use the concat function to prepend and append % character, you can simply use it as follows:
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE '%{$filter}%'");
could you not use
rowCount() ?
so it should look something like this:
$stmt = $DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
$numrows=$stmt->rowCount();
$error= $stmt->errorInfo();
echo $error[2];
if($numrows) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
I am trying to create a php script that selects one row from my table by using the WHERE clause. The problem is the mysql query returns no rows. I know the variable is correct (its user submitted).
$title = mysql_real_escape_string($_REQUEST["title"]);
$query = mysql_query("SELECT * FROM links WHERE title ='$title'", $con)
or die ("Error: " . mysql_error());
I'm looking for any ideas that could fix my problem. I know the mysql is working properly because other queries execute fine. The title variable is correct; it is passed from a mysql on another page.
ps - I posted a similar question earlier, but worded it poorly and got results that didn't address the problem
Try this:
$query = mysql_query("SELECT * FROM links WHERE title ='$title' limit 1")
or die ("Error: " . mysql_error());
Sorry, I'm new here and I couldn't find the button to comment on the original question.
But you mentioned the request was user submitted. Are they typing it or is it a selection like from a select box or radio button? I'm asking because does the requested title even exist in the DB?
Anyway, what is your result if you use the following?:
$query = mysql_query("SELECT * FROM links WHERE title LIKE '%".$title."%'")
or die ("Error: " . mysql_error());
If not, then there's definitely no match in the DB.
try this query
mysql_query("SELECT * FROM links WHERE title like '$title%'", $con)
Try this query:
$query = mysql_query("SELECT * FROM links WHERE title LIKE '%{$title}%'");
or maybe this to check formatting:
$sql = sprintf("SELECT * FROM links WHERE title LIKE '%%%s%%'", $title);
$query = mysql_query($sql);
In my case I had empty space before and after the variable name, like this
$query = "select * from user where user_name = ' $user_name ' ";
and this results in comparing userName with [empty_space userName empty_space ] which doesn't exist in the database.
your query should be like this
$query = "select * from user where user_name = '$user_name' ";