search a single word in a column - php

I want to fetch the one word out of the 4 words in the column category. For example I search for Buffet and the restaurant that has Buffet will display. This is my code so far and unfortunately it doesn't work.
HomeController
public function searchresto(){
$searchinfo = $_POST['searchinfo'];
$this->load->model('RestoModel');
$restaurantinfo['restaurantinfo']=$this->RestoModel>searchRestaurant($searchinfo);
$this->load->view('pages/searchDisplay',$restaurantinfo);
}
RestoModel
public function searchRestaurant($searchinfo){
$sql = "SELECT * FROM restaurants WHERE restoname = '$searchinfo' OR restocuisines = '$searchinfo' OR category = '$searchinfo'";
$result = $this->db->query($sql);
$result = $result->result('array');
return $result;
}

First, sanitize user input. Never query the database directly from the user input, as this may cause SQL Injection.
After sanatizing the user input, try using the LIKE function.
For example:
SELECT 'Breakfast, Lunch, Dinner, Buffet, Snack' LIKE '%Lunch%' would output 1.
SELECT 'Breakfast, Lunch, Dinner, Buffet, Snack' LIKE '%NonExistantCategory%' would output 0.
Try changing your query to SELECT * FROM restaurants WHERE category LIKE '%$searchinfoSanatized%', where $searchinfoSanatized is the input that has been filtered/escaped.
Also, I believe you are forgetting a - after RestoModel: $restaurantinfo['restaurantinfo']=$this->RestoModel>searchRestaurant($searchinfo);

Related

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

Only one query instead of two

I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Comparing strings returned from a mySql query

I am querying a large number of codes from my database, and need to have some validation before a user can input another code in to the database.
An example code would be this:
TD-BR-010212-xxxxxxxx
Where TD represents a promotion, BR represents a place, the numbers represent a date, and the rest are random.
My problem is that before the code is entered into the DB, I want to check to see if the date and place for that code already exists, as they should not be allwed to enter a code from the same place and date.
I assume it would be something within a loop as I already have:
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
But Im just not sure about the best way to check the strings..
You can use a MySQL LIKE clause to get entries in your DB that resemble your code.
Example:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
The '%' is used as a wildcard in SQL LIKE clauses.
You have two approach to solving this issue. Assuming you have access to alter the table.
Add a unique constraint to the table base off of the two columns.
Or Your approach by selecting all of the Location and Date, and see if it return any results.
SQL: SELECT COUNT(*) as counter FROM table where column = 'TD-BR-010212-%'
And check to see if counter return > 0;
I would use the LIKE statement in your SELECT and pull entries that start with the same promotion, place, and date. Unfortunately I don't know how your table looks so bear with me:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
try this query
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
If you can, you'll get better performance and easier coding if you break apart the code into different fields when you save the data in each row. That way you can write queries that specifically check values for the components pieces of the code - you can even set rules in the database (like UNIQUE) to ensure that some parts are kept unique.
Specifically, I'd suggest:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
Your first row would be ([...], 'TD','BR','2012-01-02', 'xxxxxxxx'). And queries would not require unpacking the formatted string - you could say things like "where promotion = 'TD' and place in ('BR','XX') ...". Simple, eh?

Search suggestion box inputs space in front of search query

We have a problem with our search suggestions. Everytime we click on a suggestion at our website, it puts a space in front of the search query, which causes the query to fail.
The code that we use for the suggestions is this:
$query = $db->query("SELECT DISTINCT productnaam FROM product WHERE merk LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->merk.' '.$result->productnaam.'\');">'
.$result->merk.' '.$result->productnaam.''.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
Try out with trim()
$queryString = trim($queryString);
The trim() function removes whitespaces and other predefined characters from both sides of a string.
try the trim() function as Sameera Thilakasiri specified below and also update your query to something like "SELECT DISTINCT productnaam FROM product WHERE merk LIKE '%$queryString%' LIMIT 10" The percent sign on both sides will ensure that your query will select records that contain your input as opposed to records that start with your input.
bellow is some further explanation on the SQL LIKE condition that might help you out
// This query will look for records that start with "sa"
select * from table where name like 'sa%'
// This query will look for records that contain "sa"
select * from table where name like '%sa%'
// This query will look for records that end with "sa"
select * from table where name like '%sa'
hope that helps!

Categories