MySQL - Delete value in the row, instead of deleting the row - php

I want to delete the searched value (not row) if a row contains the searched value. For example, if I want to remove banana, it should only remove banana from the rows which contain banana.
Tried this,
DELETE FROM users where eat like '%banana%'
However, it removes the rows. So how can I remove only search value from the rows ?

You can try this -
UPDATE users SET eat = REPLACE(eat, 'banana', '') where eat like '%banana%';
This would replace only banana from eat column where it is present.
Update
Loop through the data and replace those values. This might help -
$check_val = 'banana';
//select those rows first
"select id, eat from users where eat like '%" . $check_val . "%'"
foreach($data as $v) {
$temp= explode(',', $v['eat']);
$temp= array_map(function($t) use($check_val) {
return (strpos($t, $check_val) !== false) ? null : $t;
}, $temp);
$temp = array_filter($temp);
$v['eat']= implode(',', $temp);
"update users set eat= '" . $v['eat'] . "' where eat like '%" . $check_val . "%'"
}

UPDATE users SET eat = null where eat like '%banana%';
OR
UPDATE users SET eat = '' where eat like '%banana%';

Update users
set eat = 'your value'
where eat like '%banana%' ;

Try this query :
update users set eat='' where eat like '%banana%'

Related

MySQL - Return all values if input is empty

I am creating an advanced search feature for a website and it's almost done, I'm only having one major issue.
I am matching the rooms like this:
AND Rooms=" .$_SESSION["room"] ."
and tried this as well:
AND (Rooms=" .$_SESSION["room"] ." OR Rooms IS NULL)
But the problem is if the user doesn't insert any value in the room input it won't show any room. And with the IS NULL code if I insert "8" in the rooms input if there is no matches it will display all values from the DB.
I don't want to make the input as required.
I just need a solution with mysql for when the field is empty return all values without using this:
if ($_SESSION["room"]==NULL) {}
else{}
Full query:
`SELECT * FROM secret WHERE secretIDName='1' AND NatureTypeIDName LIKE '%" .$_SESSION["nature"] ."%' AND (NettArea>="
.$_SESSION["NettArea"] ." OR NettArea IS NULL) AND ConditionTypeIDName LIKE'%" .$_SESSION["lifestyle"]
."%' AND ((SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1)>="
.$_SESSION["BusinessTypeValuesMin"]
." AND SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1)<="
.$_SESSION["BusinessTypeValuesMax"]
.") OR SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1) = '') AND (SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',2),'|',-1)='"
.$_SESSION["BusinessTypeValuesType"]
."' OR SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',2),'|',-1)='') AND GarageArea>="
.$_SESSION["GarageArea"]
." AND (LocationIDName LIKE '%"
.$_SESSION["zone1"]
."%' AND LocationIDName LIKE '%"
.$_SESSION["zone2"]
."%' AND LocationIDName LIKE '%"
.$_SESSION["zone3"]
."%') AND (Rooms="
.$_SESSION["room"]
.") LIMIT "
.($page-1)*$Page
.", " .$Page ."";`
You can create the condition like this (I assume, that the "rooms" is number representing number of rooms?):
AND (Rooms = ".(int)$_SESSION['room']." OR ".(int)$_SESSION['room']." = 0)
If $_SESSION['room'] is empty (user haven't specified number of rooms), You get
AND (Rooms = 0 OR 0 = 0)
... which is always TRUE, so the "rooms" condition doesn't apply at all. If user specified number of rooms, the query would look like:
AND (Rooms = 8 OR 8 = 0)
The 8 = 0 is always FALSE, so effectively, You have the condition You need: Rooms = 8.
In your query, checking NULL isn't the same as checking empty. I'd recommend the following:
AND (Rooms=" .$_SESSION["room"] ." OR Rooms IS NULL OR Rooms <>'')
Also, it's highly recommended filtering the $_SESSION variable before injecting that into MySQL, if it's a number, assign it to $room=(int)$_SESSION['room'] to force it to be an integer.
There are several solutions, one of them is simply to store the SQL in a string variable, and then add the rooms conditions if the value is not null.
$sql = SELECT ...
if ($_SESSION["room"] !== NULL) {
$sql = $sql . ' AND Rooms=".$_SESSION["room"] . " '
}
Try the query like this: Note i concatenate all php varibles with {} instead of ". ."
SELECT * FROM secret WHERE secretIDName='1' AND NatureTypeIDName LIKE '%{$_SESSION["nature"]}%' AND (NettArea >={$_SESSION["NettArea"]} OR NettArea IS NULL) AND ConditionTypeIDName LIKE'%{$_SESSION["lifestyle"]}%' AND ((SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1)>={$_SESSION["BusinessTypeValuesMin"]} AND SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1)<={$_SESSION["BusinessTypeValuesMax"]}) OR SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',4),'|',-1) = '') AND (SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',2),'|',-1)='{$_SESSION["BusinessTypeValuesType"]}' OR SUBSTRING_INDEX(SUBSTRING_INDEX(BusinessTypeValues,'|',2),'|',-1)='') AND GarageArea>={$_SESSION["GarageArea"]} AND (LocationIDName LIKE '%{$_SESSION["zone1"]}%' AND LocationIDName LIKE '%{$_SESSION["zone2"]}%' AND LocationIDName LIKE '%{$_SESSION["zone3"]}%') AND (Rooms={$_SESSION["room"]}) LIMIT ($page-1)*$Page, $Page";

fetching records with same random word in specified column in mysql

I have following data in table,
id Description Category
1 I am Desc with printer main category
2 I am desc with test test category
3 new printer desc third category
4 new test category printer category
and So on....
I want to find count having same word(Which can be anything like printer but not predefined) in their description field.
For ex Output should be:
Total Word which is same
2 printer
2 test
I tried using http://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html example with boolean option but its not giving desired output.
Here is example I given is printer which can be anything.
I dont want to specify this word in query anywhere because it can be anything.
only description having same words anywhere should be in output.
Thanks in Advance.
try this :
SELECT SUM(IF(Description like '%printer%',1,0)) AS Printer,SUM(IF(Description like '%test%',1,0)) AS Test FROM `yourTable`
this might be help :)
Build a dictionary of all the words in the descriptions
$dbh = new PDO($dsn, $user, $password);
$sql = "SELECT description FROM tableName";
foreach($dbh->query($sql, PDO::FETCH_ASSOC) as $result){
foreach (explode(' ',$result['description']) as $word){
$words[] = $word;
}
}
Count the duplicate values in the array using array_count_values, optionally sort it descending
$wordCount = array_count_values($words);
arsort($wordCount);
Then filter the array to eliminate the words that occur just once using array_filter
$filteredWordCount = array_filter($wordCount, function($value){
return $value!=1;
});
this should give you an array that has the words themselves as indexes and the number of occurrences as values.
Iterate over the array and run a COUNT query
foreach($filteredWordCount as $word=>$value){
$countSQL = 'select COUNT(*) as rowCount from tableName where description like "%' . $word . '%" ';
$res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
$count[$word] = $res->fetch()['rowCount'];
}
Sort the array on the values, like before, and print it out
arsort($count);
print_r($count);
If you need a condition on the number of rows, for example, return only words that appear in more than 5 records you can adjust the query like this
foreach($filteredWordCount as $word=>$value){
$countSQL = 'select COUNT(*) as rowCount from domains where description like "%' . $word . '%" HAVING rowCount > 5';
$res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
$c = $res->fetch()['rowCount'];
if (isset($c)){
$count[$word] = $c;
}
}

Find string in two field with SQL

I'm working on a search module, like facebook when you look for a friend.
So, i have in my table user two fields : firstname and name.
If i have for example a user : firstname : Georges and name : Clooney, i want, when i write :
Geo...
Cloo...
loo geor...
geor ney
etc....
retrieve this user.
How can i do that with SQL ? I want to write a very permissive search module..
This will surely help you
Well the below method first calculate all possible combination of the possible words & then matches it with database
<?php
$name ='Georges Clooney'; // you search string
$words=explode(" ", $name);;
function get_all_combination($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
get_all_combination($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
get_all_combination($words, "", $collect);
/*
$collect now have all possible combination of search string
Array
(
[0] => Georges
[1] => Georges Clooney
[2] => Clooney
[3] => Clooney Georges
)
*/
$sql="SELECT * FROM user_info WHERE (firstname like '%".implode("%' OR firstname like '%",$collect)."%' or name like '%".implode("%' OR name like '%",$collect)."%')" ;
?>
For any more help do ask
What you need, is this little Friend: %
WHERE firstname LIKE '%" . $name . "%' OR name LIKE '%" . $name ."%'
Here is a tutorial:
http://www.webreference.com/programming/php/search/index.html
Try This:
Select * from User where `name` LIKE '%search_string%' OR `firstname`
LIKE '%search_string%' OR CONCAT(firstname,' ',name) LIKE '%search_string'%'
SELECT *
FROM User
WHERE firstname LIKE '%'+#input+'%' OR name LIKE '%'+#input+'%'
where #input is the inserted text in the textbox.
Try this query:
SELECT * from user
WHERE name LIKE '%search_string%'
OR firstname LIKE '%search_string%'
It will match if any firstname or name containing search_string. it will show all users containing this string in name or first name.
Try this
select * from user where `name` like '%trim(search_string)%' OR `firstname`
like '%trim(search_string)%' OR CONCAT(firstname,' ',name) LIKE '%".trim(search_string)."%';
Also concat both the fields and try to match.

Get multiple results using LIKE

Say I have some records in my database with data like so:
John Murdoch
I am John Murdoch
My first name is john and my second name is murdoch
I have a search form and I type in "john murdoch" which will run this query:
$search //contain the search string in this case is john murdoch
$sql = mysqli_query($sql, "SELECT * FROM table WHERE column LIKE '%$search%'");
while($row = mysql_fetch_assoc($sql)){
echo $row['first']."<br>";
}
This will return the first two rows only because it is only those rows that have the both words beside each other. How can I return the other row even though the words are split up? I know I could explode the string and check each piece, but I was looking for a more stable and efficient way of doing this.
Just replace punctuation and spaces with the wildcard % before your query.
$search = str_replace ( array( '.', ' ', "'", '-' ), '%', $search );
This does still require the first word to appear in the text before the second word. So if your search was for "Murdoch John", you would not return any results.
The better answer is to employ FULLTEXT searching on the column (must do this in MySQL), and do a MATCH() query against the column, like so:
Add a plus sign before each word (to indicate that word is required)
$words = '+' . str_replace( ' ', ' +', $search );
And your query:
SELECT * FROM table MATCH ( column ) AGAINST ( '$words' IN BOOLEAN MODE)
More info here: http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html
SELECT * FROM table WHERE `column` LIKE '%john%' AND `column` LIKE '%murdoch%'
I would construct that query like this:
$search_terms = array('john','murdoch');
$field_to_search = 'some_column';
$sql = 'SELECT * FROM table WHERE' . "\n";
$sql .= '`' . $field_to_search . '` LIKE \'%'
. implode('%\' AND `' . $field_to_search . '` LIKE \'%',$search_terms)
. '%\'';
That PHP can be used with any number of search terms. It requires matches for all because it's connected with AND.
Here's a link to a php fiddle: http://phpfiddle.org/main/code/igv-3qc

Swapping a string where space is found in php

I need to implement the following functionality:
I have a name field which contains both name and surname. This is stored in a database and is in the order 'surname name'.
I am implementing a script which searches through these records. Currently, I managed to check if a string contains a space, if it contains a space it means it is a name and not an ID Card Number for instance. Here is the code:
$query = "John Doe";
$checkIfSpaceExists = strpos($query, " ");
if ($checkIfSpaceExists == "")
{
//No Space therefore it is not a name
}
else
{
//Contains space
$queryExploded = explode(" ", $query);
foreach ($queryExploded as $q)
{
//Here I need the functionality so that if someone entered John Doe
//2 different strings are saved, which are
//$string1 = John Doe
//$string2 = Doe Johns
//If the name consists of 3 parts, strings for every combination is saved
}
Then I will insert these strings in an SQL statement with the LIKE attribute and there will be a LIKE for both JOHN DOE and DOE JOHN. Hence, if the user can either enter John Doe or Doe John in order to find the result.
Any suggestions on how to do this?
Many thanks
chris
Ok, from the start - be sure to read the manual carefully. strpos doesn't do exactly what you think it's doing. Here's how you should check for a space:
if (strpos($query, ' ') === false) // the triple-equals is important!
After that, it's simply a matter of permutations and combinations. Here's another answer on Stack Overflow which shows you how to do it: algorithm that will take number or words and find all possible combinations
What about using these exploded 3 strings in separate AND-combined LIKE-constraints?
Something like
"... WHERE name LIKE '%$name[0]%' AND name LIKE '%$name[1]%' AND name LIKE '%$name[2]%'"
You could build this String in a foreach loop.
echo preg_replace('/^(\w+) (\w+)$/', '$2 $1', "John Doe");
Doe John
I guess you cannot split this field into name and surname? I suggest creating new table, tags in database. Tags will be any word - might be surname, may be name, may be ID number... Then make a connection record_tags with record_id and tag_id. Then the query will look like
SELECT record.* FROM record
INNER JOIN record_tags rt1 ON rt1.record_id = record.id
INNER JOIN tag t1 ON t1.id = rt1.tag_id
INNER JOIN record_tags rt2 ON rt2.record_id = record.id
INNER JOIN tag t2 ON t2.id = rt2.tag_id
WHERE
t1.name = "John"
AND t2.name = "Doe"
This will be better approach to searching, as you can then use any amount of words/tags. I think the SQL can be even easier. the multiple-like approach is I think much slower, especially as your database grows.
With some looping and string manipulation, I managed to implement this script.
Here is what I did:
I checked if the query contains a space using strpos. If it contains a space, then it means its a name with both name and surname so I enter a loop in order to output one string with 'name surname' and the other string with 'surname name'
Here is the code:
$like = ""; //This is the LIKE sql command.
foreach ($selectedFields as $field)
{
$checkIfSpaceExists = strpos($query," ");
if ($checkIfSpaceExists != "")
{
$query1 = $query; //No space, so query1 is equal ta original query
$queryExploded = explode(" ", $query);
for ($i=0; $i<count($queryExploded); $i++) //First loop (name surname)
{
$tmp1 = $tmp1 . " " . $queryExploded[$i];
}
for ($i=count($queryExploded); $i>=0; $i--) //Second loop (surname name)
{
$tmp2 = $tmp2 . " " . $queryExploded[$i];
}
$query2 = $tmp2;
$query2 = trim($query2);
$like = $like . $field . " LIKE '%" . $query1 . "%' or " . $field . " LIKE '%" . $query2 . "%' or ";
I hope this helps someone else in need :)

Categories