How to highlight user input in mysql search results using php? - php

I have added my code below, i am new to php and mysql and trying to search mysql using php based on user inputs and working really fine. But not sure how to highlight the user input value while displaying from mysql.
$output = NULL;
if(isset($_POST['submit'])){
$mysqli = new mysqli("localhost","root","","test");
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM books WHERE BookContent LIKE '%$search%'");
if($resultSet->num_rows>0){
while($rows = $resultSet->fetch_assoc()){
$BookContent = $rows['BookContent'];
//$output = preg_replace("/($search)/i",'<span class="highlight">$1</span>', $output);
echo $output = "" ."Your search results--> $BookContent"."<br>";
}
}else{
echo $output = "No result" ;
}
}
?>

just add this in your page.
CSS:
.highlight{background-color:yellow}
jQuery:
$("body").highlight("<?php echo $search; ?>");

Related

php is not connecting with mysql

I want to perform a query on a database with genomic information.
This is part of the php code:
$db = mysqli_connect($servername,$username,$password,$database)
$fields = "name, chrom, strand, txStart, txEnd, exonCount, name2";
$query = "SELECT $fields FROM $table WHERE name2 LIKE '%$gene%';";
$result = mysqli_query($db,$query);
$items = mysqli_affected_rows($result);
if ($items == 0)
{
print_error("The gene $gene is not found in the RefSeq database");
}
else
{
$transcripts = $items;
echo "<html>\n";
echo "<head>\n";
echo "<title> Catalogue web server </title>\n";
echo "<link href=\"styles.css\" rel=\"stylesheet\">\n";
echo "</head>\n";
echo "<body>\n";
echo "<h1>Catalogue output ($gene)</h1>\n";
echo "<table>\n";
echo "<tr><th>GENE</th><th>TRANSCRIPTS</th><th>CHR</th><th>STRAND</th><th>POS1</th><th>POS2</th><th>EXONS</th>\n";
for ($i = 0; $i<$items; $i++)
{
$row = mysqli_fetch_array($result);
$name2 = $row["name2"];
$name = $row["name"];
$chrom = $row["chrom"];
$strand = $row["strand"];
$txStart = $row["txStart"];
$txEnd = $row["txEnd"];
$exonCount = $row["exonCount"];
echo "<tr><td>$name2</td><td>$name</td><td>$chrom</td><td>$strand</td><td>$txStart</td><td>$txEnd</td><td>$exonCount</td>\n";
}
echo"</table><br><br>\n";
}
However, when I submit the query from html localhost, I´m always getting the error message:
The gene is not in the database
When I know it is.
Any help finding the error would be appreciated it.
ALSO: $servername, $username, $password and $database are correct, checked several times
I don´t mind about mysql injections as I´m not publishing this web
Try instead with:
$items = mysqli_num_rows($result);
The mysqli_affected_rows is used after insert, update, replace or delete queries.

Php won't show requested data from database (sql)

Im trying to display all the movies with specific hashtag.
The results are not showing but there are no errors.
However i should get movie poster image and title as result. :/
In my database, this is 'tags' row of one movie
#watchonline #movies-with-subs #hdmovies
and tag.php
<?php
require "db.inc.php";
if (isset($_GET['tag'])) {
$tag = preg_replace('#[^a-z0-9_-]#i', '', $_GET["tag"]);
$fulltag = "#" . $tag;
echo $fulltag;
$ASDsql = "SELECT * FROM movie WHERE tags LIKE '$fulltag' OR tags =
'$fulltag'";
$tagQuery = mysqli_query($db, $ASDsql);
$count = mysqli_num_rows($tagQuery);
if($count > 0) {
while ($hastags = mysqli_fetch_array($tagQuery)) {
$id = $hastags['id'];
$movie_title = $hastags['movie_title'];
$movie_url = $hastags['movie_url'];
$movie_image = $hastags['movie_image'];
$movie_identity = $hastags['movie_identity'];
echo "<div class='item'><a href='movie.php?movie=$id'><img
src='$movie_image'><p>$movie_title</p></a></div>";
}
}else {
echo "No movies under that tag";
}
}
?>
I've checked db.inc.php file it's all good.
My output is "No movies under that tag";
Im sorry if this is a copy i really looked and could not find an answer
try this :
$ASDsql = "SELECT * FROM movie WHERE tags LIKE '%$fulltag%' OR tags =
'%$fulltag%'";
or may be the table is not having any value

My PHP Search Function isn't Outputting Data

So I am trying to create a way of searching my website. I've created a search bar on my index page. You can find this page here: http://seersvillage.com/v1.2/
My search form looks like this:
<form method="post" action="search.php">
<input type="text" name="search" class="search" value="Skeleton" onFocus="this.value=''">
</form>
and I have a functions.php file attatched and this page is also connected to my mysql database. I have content available to be read / searched for all ready.
Here is my search function on functions.php:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
}
}
And the only thing on my search.php (excluding your usual html layout) is as follows:
<?php
include('includes/functions.php');
if(!isset($_POST['search'])) {
header("Location:index.php");
}
?>
and further down in the tags.
<?php print("$output");?>
Now I am pretty new to PHP and MySQL. However I am getting no error on my error.log file, making troubleshooting a little hard for a first timer. Any suggestions? I'm sure it's a very simple mistake, probably just misspelt something, but I just can't see it.
it seems that your php.ini file is set to not display errors. Add these lines of code at the beginning of your code and retry:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Your doSearch function does not return anything.
return $output;
But $output is only declared within the function. So you'll need to use
print(doSearch());
Either that or declare $output as a global variable, but we don't want to do that :)
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
//make sure your function returns $output
return $output;
}
Make sure your function returns the output and then echo out the function:
<?php echo doSearch(); ?>
This is because of how PHP variables are scoped.
...then of course we need to add in all the standard provisos ... don't use the mysql_ library it's almost as dead as a Norwegian Blue. If you use mysqli or PDO you can bind the parameters/values to a prepared statement and not only will that improve efficiency but it'll ensure your input is properly sanitised (far better than that odd ad-hoc preg_replace you're using).
You don't want to kill your script (die) when the query fails - that's just a bit weird, handle the error properly.
There are far better ways to do searches in SQL such as FULLTEXT searches.. or if you can, perhaps implement Apache Solr rather than trying to roll your own.

jquery autocomplete with php file that queries a mysql database

i'm trying to use a jquery autocomplete text-input with a mysql database for autocomplete suggestions. From a tutorial i got the following php function that is used to query a database.
<?php
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT planeID FROM `planes` WHERE `planeID` LIKE '%$search%' ")
or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['planeID'].'"}';
}
$json .= ']';
echo $json;
within the chrome networkpanel, i can see, that after each input into my textfield a request to "suggest_planeID.php?term=d-" i sent but i don't reveive any suggestion.
the database looks like this:
i have ha DatatBase called "test" with a table caled "planes" inside. This table has two columns 'planeID' and 'planeType".
is there any chance to debug the php file to find the error or does anyone here already see the error?

Search A Single String In MySQL

I am making a private message system and i created a php search page, I am using JQuery to pass a variable from a text field on keyUp to a PHP file called USearch.php or Username Search. Here is my code:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'] = $User;
}
}
}
echo json_encode($USearch);
?>
As you can see, my code has no errors, my problem is that i am searching Users in a DB which means i am searching 1 word or string, by using this PHP code, i would have to type in the exact username for the function to return a value. My real intention was to search the string and return all similar usernames according to my input string.
Like Jon said - you want to use % where you want your SQL to have a wild card.
If you want all values where name is like matt you would do
WHERE name LIKE '%matt%'

Categories