mysql search using for loop from php - php

i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>

In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}

Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>

You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.

Related

How to implement REGEXP in foreach the right way?

Hello,
How to add regexp the right way in this code in order to search for exact word in database?
$condition = '';
$name = "he is mad";
$query = explode(" ", $name);
foreach($query as $text) {
$condition .= "test LIKE '%".mysqli_real_escape_string($conn, $text)."%' OR ";
}
$condition = rtrim($condition, " OR ");
$sql_query = "SELECT * FROM test WHERE " . $condition;
$result = mysqli_query($conn, $sql_query);
if ($result->num_rows > 0) {
echo "1";
} else {
echo "0";
}
$conn->close();
I want to add this to the php code
SELECT
*
FROM
`table`
WHERE
Description regexp '(^|[[:space:]])pen([[:space:]]|$)';
It only works with me like this without foreach:
$sql_query = "SELECT * FROM test WHERE test regexp '(^|[[:space:]])$condition([[:space:]]|$)'";
You just need to remove the last " OR " from your $condition
<?php
$condition = '';
$name = "Hello world i am so sad";
$query = explode(" ", $name);
foreach($query as $text) {
$condition .= "test LIKE '%".mysqli_real_escape_string($conn, $text)."%' OR ";
}
// HERE REMOVE LAST " OR " FROM STRING
$condition = rtrim($condition, " OR ");
$sql_query = "SELECT * FROM test WHERE " . $condition;
$result = mysqli_query($conn, $sql_query);
if ($result->num_rows > 0) {
echo "1";
} else {
echo "0";
}
$conn->close();
If you have a phrase that is separated by spaces and you want to see if there is any overlap with the words, you can possibly use regular expressions:
where col regexp replace($name, ' ', '|')
Note that you should be passing $name in as a parameter.
If you care about word boundaries, you can introduce them into the regular expression. However, the exact form may depend on which regular expression library MySQL is using. The idea is:
where col regexp concat('\\b', replace($name, ' ', '\\b|\\b'), '\\b')

How to show all matching results from the query?

I am looking to have what my 'echo' line is but if there is more than one match to the FSC/NIIN field then it should show me the additional matches.
There is more than one part number listed for some FSC/NIIN fields, I am working towards having it show those additional part numbers that match the stock number (FSC/NIIN).
<?php
require "conn.php";
$FSC = $_POST["FSC"];
$NIIN = $_POST["NIIN"];
$mysql_qry = "select * from MYTAB where FSC like '$FSC' and NIIN like '$NIIN';";
$result = mysqli_query($conn, $mysql_qry);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$PART_NUMBER = $row["PART_NUMBER"];
$FSC = $row["FSC"];
$NIIN = $row["NIIN"];
$ITEM_NAME = $row["ITEM_NAME"];
echo $ITEM_NAME, ", " .$PART_NUMBER, ", " .$FSC, ", " .$NIIN;
} else {
echo "Query Failed! - No such NSN is loaded to the database! Please double
check the information is correct and resubmit request...";
}
mysqli_close($con);
You need to loop the results:
....
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) { //<-----
$PART_NUMBER = $row["PART_NUMBER"];
$FSC = $row["FSC"];
$NIIN = $row["NIIN"];
$ITEM_NAME = $row["ITEM_NAME"];
echo $ITEM_NAME, ", " .$PART_NUMBER, ", " .$FSC, ", " .$NIIN;
}
} else {
...
And you should use prepared statements, take a look how to here:
How can I prevent SQL injection in PHP?

In my php script, my connection to the server works but my sql queries do not

The connection works, I don't get a connection error. But when I run the script I get an undefined index error and it outputs "0 results" although my table is populated for sure and I am searching for something that I know is in the table.
I am using MySQL workbench to manage the database and apache (xampp) to host the local server and run the PHP scripts. Could this be the problem? Is there a way for me to host the database in the same place as the apache website?
$sql="SELECT * FROM book_table WHERE Title LIKE $input OR Author LIKE $input OR Barcode LIKE $input";
$result = $conn->query($sql);
if ($result) {
while($row = $result->fetch_all()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
My suggestion to you is PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM book_table WHERE Title LIKE :info OR Author LIKE :info OR Barcode LIKE :info";
$ps = $db->prepare($query);
$ps->bindValue(':info', $input)
$ps->execute();
$result = $ps->fetchAll(PDO::FETCH_ASSOC);
//iterate over result
if (!empty($results)){
foreach ($result as $row) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
Also, remember to use the MySQL LIKE in the right way. When you want to match a part of a String, you need to use the % symbol.
Ex:
SELECT * FROM book_table WHERE Title LIKE "%goodbook%"
It will return all rows that has the "goodbook" as part of the Title.
You can try like this. Since you use mysqli_* I have make it prepared statements and bind_param.
Note: Not tested. So may need to adjust a bit.
$param = '$input';
$sql= $conn->prepare("SELECT * FROM book_table WHERE Title LIKE ? OR Author LIKE ? OR Barcode LIKE ?");
$sql->bind_param("s", $param);
$sql->execute();
if($res->num_rows > 0) {
while ($row = $res->fetch()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}

php Search engine the keywords are not working

When i would search for the keywords that i have specified in my database it will return everything from my database not just the corresponding links that have the keywords attached to the link. here is my code
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
$query = "SELECT * FROM search ";
foreach ($terms as $each){
$i=0;
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$query = mysql_query("SELECT * FROM search");
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
}
else
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
//disconnect
mysql_close();
?>
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
//connect
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$query = "SELECT * FROM search ";
$i=1;
foreach ($terms as $each){
if ($i == 1) {
$query .= "WHERE ";
$query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
} else {
$query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
}
$i++;
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
} else {
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
}
//disconnect
mysql_close();
?>
Fixes:
1) Removed second $query that was being defined. It selected all rows.
2) Moved initial $i declaration. It was being set back to 0 each loop.
3) Added WHERE
4) Moved $i++ after the if statement and set initial $i to 1.
5) Added mysql_real_escape_string so that data is escaped properly.
Recommendations:
I highly recommend taking a look at MySQLi (http://us2.php.net/mysqli) or PDO (http://us3.php.net/pdo)
Please let me know if this works or if you need further assistance.
A first sight, i see a couple of errors.
$i=0;
$i++;
if ($i == 1)
$i Will ALWAYS be one are.
you might want to move $i = 0; BEFORE the foreach
$query = mysql_query("SELECT * FROM search");
You build a query, but in the end you're not using it. you probably want to do : $query = mysql_query($query); instead. ( and also for code clarity using a different variable name for the output ? ) .
mysql_query is deprecated. Useless you're in a hurry, check PDO
First, you're missing the WHERE keyword before the conditions. So it should be:
foreach ($terms as $i => $each){
$each = mysql_real_escape_string($each); // Prevent SQL injection
if ($i == 0)
$query .= "WHERE keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
You don't need to increment your own counter variable, you can use the array indexes from $terms.
Second, after all that work to create $query, you're not using it. You wrote:
$query = mysql_query("SELECT * FROM search");
That should be:
$query = mysql_query($query);
BTW, it's generally a bad idea to reuse variables like that, it gets confusing when you use the same variable for different things. I suggest you call the second $query something like $results.
Change this line
$query .= "keywords LIKE '%$each%' ";
By
$query .= " Where keywords LIKE '%$each%' ";
And also cnhange this line
$query = mysql_query("SELECT * FROM search");
By
$query = mysql_query($query);

Multi word search in PHP/MySQL

I'm struggling to create a search that searches for multiple words. My first attempt yielded no results whatsoever and is as follows:
require_once('database_conn.php');
if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);
foreach($explodedSearch as $search){
$query = "SELECT *
FROM jobseeker
WHERE forename like '%$search%' or surname like '%$search%'
ORDER BY userID
LIMIT 5";
$result = mysql_query($query);
}
while($userData=mysql_fetch_array($result)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
I also tried the following, which yielded results, but as you can imagine, I was getting duplicate results for every word I entered:
if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);
foreach($explodedSearch as $search){
$query = "SELECT *
FROM jobseeker
WHERE forename like '%$search%' or surname like '%$search%'
ORDER BY userID
LIMIT 5";
$result .= mysql_query($query);
while($userData=mysql_fetch_array($result)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
}
I'm pretty much at a loss as to how to proceed with this, any help would be greatly appreciated.
EDIT:
if($_POST){
$quickSearch = $_POST['quickSearch'];
$explodedSearch = explode (" ", trim($quickSearch));
$queryArray = array();
foreach($explodedSearch as $search){
$term = mysql_real_escape_string($search);
$queryArray[] = "forename like '%" . $term . "%' surname like '%" . $term . "%'";
}
$implodedSearch = implode(' or ', $queryArray);
$query="SELECT *
FROM jobseeker
WHERE ($implodedSearch)
ORDER BY userID
LIMIT 5";
$result = mysql_query($query);
while($userData=mysql_fetch_array($result, MYSQL_ASSOC)){
$forename=$userData['forename'];
$surname=$userData['surname'];
$profPic=$userData['profilePicture'];
$location=$userData['location'];
echo "<div class=\"result\">
<img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
<p class=\"quickName\">" . $forename . " " . $surname . "</p>
<p class=\"quickLocation\"> " . $location . "</p>
</div>";
}
}
I've been working on the same subject (search with keywords) for a while and this how i did it :
$words = $_POST['keywords'];
if(empty($words)){
//redirect somewhere else!
}
$parts = explode(" ",trim($words));
$clauses=array();
foreach ($parts as $part){
//function_description in my case , replace it with whatever u want in ur table
$clauses[]="function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause=implode(' OR ' ,$clauses);
//select your condition and add "AND ($clauses)" .
$sql="SELECT *
FROM functions
WHERE
user_name='{$user_name}'
AND ($clause) ";
$results=mysql_query($sql,$connection);
if(!$results){
redirect("errors/error_db.html");
}
else if($results){
$rows = array();
<?php
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
// echo whatever u want !
}
?>
-- Now this is how it look when i tried to run it with FULLTEXT search :
But you should set the table type as "MyISAM"
<?php
$words = mysql_real_escape_string($_POST['function_keywords']);
if(empty($words)){
redirect("welcome.php?error=search_empty");
}
//if the columns(results)>1/2(columns) => it will return nothing!(use "NATURAL LANGUAGE"="BOOLEAN")
$sql="SELECT * FROM functions
WHERE MATCH (function_description)
AGAINST ('{$words}' IN NATURAL LANGUAGE MODE)";
$results=mysql_query($sql,$connection);
if(!$results){
redirect("errors/error_db.html");
}
else if($results){
$rows = array();
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
// echo
}
}
?>
Perhaps what you are looking for is a MySQL full-text search.
For your example, you could do something like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$search = $_POST['quickSearch'];
// Todo: escape $search
$sql = "
SELECT
*,
MATCH (`forename`)
AGAINST ('{$search}' IN NATURAL LANGUAGE MODE) AS `score`
FROM `jobseeker`
WHERE
MATCH (`forename`)
AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)";
// Todo: execute query and gather results
}
Note that you will need to add a FULLTEXT index to the column forename.
Take a look at MySQL fulltext searches, if you must use MySQL. Otherwise take a look at SOLR, which is a fulltext search engine. You can use MySQL and SOLR in combination to provide enterprise level search capabilities for your apps.
here's what i did
if (isset($_POST['search'])){
$words = mysql_real_escape_string($_POST['searchfield']);
$arraySearch = explode(" ", trim($words));
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM parts WHERE ";
$quote = "'";
while ($a < $countSearch)
{
$query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
$a++;
if ($a < $countSearch)
{
$query = $query." AND ";
}
}
$result=mysql_query($query) or die(error);
//you could just leave it here, short and sweet but i added some extra code for if it doesnt turn up any results then it searches for either word rather than boths words//
$num = mysql_num_rows($result);
if ($num == 0){
$a = 0;
$query = "SELECT * FROM parts WHERE ";
while ($a < $countSearch)
{
$query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
$a++;
if ($a < $countSearch)
{
$query = $query." OR ";
$msg = "No exact match for: $words. Maybe this is what you're looking for though? If not please try again.";
}
}
}
$result=mysql_query($query) or die($query);
if (mysql_num_rows($result) == 0){
$msg = "No results, please try another search";
}
}

Categories