Select record using FIND_IN_SET - mysql

I am storing the check box value as comma separated value in db like
Features
1,3,4
1,2,3,4,5
3,4,5,6
Now while searching i need to select the record based on the user select the check-box, say example if user selects 1 and 6 needs to fetch matched record. I am getting selected check-box value as array like (0=>1,1=>6). I dont know how to loop through this like FIND_IN_SET(1,Features) OR FIND_IN_SET(6,Features)
It has to come like
SELECT * FROM table WHERE FIND_IN_SET(1,Features) OR FIND_IN_SET(6,Features)

$str='%';
foreach($array as $val)
{$str.=$val.'%';}
SELECT * FROM table WHERE Features like $str
Update:
$str='';
foreach($array as $val)
{$str.='or Feature like %'.$val.'%';}
$str[0]='';$str[1]='';
SELECT * FROM table WHERE $str

I fixed using the below code to get query like this SELECT * FROM table WHERE FIND_IN_SET(1,Features) OR FIND_IN_SET(6,Features)
if($selCount >1){
foreach($luxPropFeatures as $val) {
$str .="OR FIND_IN_SET('".$val."',LP.luxury_property_feature_id) ";
$trimmed = ltrim($str, "OR");
//$str[0]='';$str[2]='';
}
}else{
foreach($luxPropFeatures as $val) {
$trimmed = "FIND_IN_SET('".$val."',LP.luxury_property_feature_id) ";
}
}

Related

How to compare Comma Seperated value to get existing value

I have Table as Production with field name as production_code
Production_code have value like this,
Id production_code
1 P101,P102,P103,P105
2 P103,P106,P102
3 P104
4 P102,P105,P111
------ I have value on PHP page like $p_code='P102,P109';
Now I want to fetch rows from Table Production_code where any code is exist in production_code of variable $p_code
please help me .. what mysql query should i use
You can use function FIND_IN_SET, like:
SELECT * FROM yourTable
WHERE FIND_IN_SET('P102', production_code) OR FIND_IN_SET('P109', production_code)
Solution.
<?php
$p_code='P102,P109'; //example
$condition = '';
foreach(explode(',',$p_code) as $r){//explode convert $p_code string into array. then apply foreach for compare every element of array From database saved value
$condition .= 'FIND_IN_SET("'.$r.'", production_code) OR ';
}
$condition = rtrim($condition,' OR '); //this remove last occurence of OR from condition
echo $sql = 'SELECT * FROM yourTable
WHERE '.$condition;
?>

Select values which contains specific characters even if it's not in the same order

My problem is that I want an SQL Query that will allow me to select values which contains specific characters even if it's not in the same order.
This is my list:
https://img11.hostingpics.net/pics/729697contacts1.png
I want to show only values that contain the characters rachid even if it's not in order, or the word contain some other characters in it, this is what I should obtain:
https://img11.hostingpics.net/pics/706919contacts2.png
Thanks
SELECT *
FROM [table_name]
WHERE name <> 'hahaha' and name <> 'hhhhhh'
This would display all of your records and hide 'hahaha' and 'hhhhhh'
UPDATE:
SELECT *
FROM [table_name]
WHERE name LIKE '%rachid%' OR
WHERE name LIKE '%rach id%' OR
WHERE name LIKE '%rach'id%' OR
WHERE name LIKE '%rach ide%'
This would give you any row where rachid matches at any point in the name field.
You would have to keep adding like statements to cover other options.
I think you're also talking about distinct values so for that you would need -
SELECT DISTINCT.....
You probably want fuzzy logic. MySql doesn't support such thing out of the box. I found "Levenshtein distance" in this context. You should read about it.
You could generate a search value list from outside the sql.
Little php example:
function getLevenshtein1($word)
{
$words = array();
for ($i = 0; $i < strlen($word); $i++) {
// insertions
$words[] = substr($word, 0, $i) . '_' . substr($word, $i);
// deletions
$words[] = substr($word, 0, $i) . substr($word, $i + 1);
// substitutions
$words[] = substr($word, 0, $i) . '_' . substr($word, $i + 1);
}
// last insertion
$words[] = $word . '_';
return $words;
}
https://gordonlesti.com/fuzzy-fulltext-search-with-mysql/

Skipping a query field on IF condition

My MySQL query is sent to a csv, and then to a HTML file.
When I do...
SELECT
field_a,
IF($VAR="yes",field_b,""),
field_c
FROM table
INTO OUTFILE "query.csv";
...I always get 3 columns (field_a, field_b or empty, field_c), as expected.
How can I get only 2 columns (field_a, field_c) when $VAR is not "yes"?
Build your query dynamically. It looks like your $VAR condition does not depend on the data. Then you may do this (example in PHP):
$fields = 'field_a' ;
if ($VAR == 'yes') $fields .= ', field_b' ; // and so on
$query = "SELECT $fields FROM table" ;

mysql - insert many to many relationship

I am trying to insert records in 2 different mysql tables. Here's the situation:
Table 1: is_main that contains records of resorts with a primary key called id.
Table 2: is_features that contains a list of features that a resort can have (i.e. beach, ski, spa etc...). Each feature has got a primary key called id.
Table 3: is_i2f to connect each resort id with the feature id. This table has got 2 fields: id_i and id_f. Both fields are primary key.
I have created a form to insert a new resort, but I'm stuck here. I need a proper mysql query to insert a new resort in the is_main table and insert in is_i2f one record for each feature it has, with the id of the resort id id_i and the id of the feature id id_f.
$features = ['beach','relax','city_break','theme_park','ski','spa','views','fine_dining','golf'];
mysql_query("INSERT INTO is_main (inv_name, armchair, holiday, sipp, resort, price, rooms, inv_length, more_info)
VALUES ('$name', '$armchair', '$holiday', '$sipp', '$resort', '$price', '$rooms', '$length', '$more_info')");
$id = mysql_insert_id();
foreach($features as $feature) {
if(isset($_POST[$feature])) {
$$feature = 1;
mysql_query("INSERT INTO is_i2f (id_i, id_f) VALUES (" . $id . ", ?????????????? /missing part here????/ ); }
else {
$$feature = 0; }
}
Thanks.
Please, I'm going CrAzY!!!!!!!!!!!!!!
This may not be relevant to you, but...
Would it not make more sense to leave the link table unpopulated? You can use JOINs to then select what you need to populate the various views etc in your application
i.e. query to get 1 resort with all features:
SELECT
Id,
f.Id,
f.Name
FROM IS_MAIN m
CROSS JOIN IS_FEATURES f
WHERE m.Id = $RequiredResortId
Please find the answer on Mysql insert into 2 tables.
If you want to do multiple insert at a time you can write a SP to fulfill your needs
If I understand you correctly you could concatenate variable amount of to be inserted/selected values into one query. (This is the second query which needs an id from the first.)
//initializing variables
$id = mysql_insert_id();
$qTail = '';
$i = -1;
//standard beginning
$qHead = "INSERT INTO `is_i2f` (`id`,`feature`) VALUES ";
//loop through variable amount of variables
foreach($features] as $key => $feature) {
$i++;
//id stays the same, $feature varies
$qValues[$i] = "('{$id}', '{$feature}')";
//multiple values into one string
$qTail .= $qValues[$i] . ',';
} //end of foreach
//concatenate working query, need to remove last comma from $qTail
$q = $qHead . rtrim($qTail, ',');
Now you should have a usable insert query $q. Just echo it and see how it looks and test if it works.
Hope this was the case. If not, sorry...

MySQL: How can fetch SUM() of all fields in one Query?

I just want somthing like this:
select SUM(*) from `mytable` group by `year`
any suggestion?
(I am using Zend Framework; if you have a suggestion using ZF rather than pure query would be great!)
Update: I have a mass of columns in table and i do not want to write their name down one by one.
No Idea??
SELECT SUM(column1) + SUM(column2) + SUM(columnN)
FROM mytable
GROUP BY year
Using the Zend Framework's Zend_Db_Select, your query might look like
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from('mytable', array('sum1' => 'SUM(`col1`)', 'sum2' => 'SUM(col2)')
->group('year');
$stmt = $select->query();
$result = $stmt->fetchAll();
Refer to the Zend_Db_Select documentation in the ZF manual for more.
EDIT: My bad, I think I misunderstood your question. The query above will return each colum summed, but not the sum of all of the columns. Rewriting Maxem's query so that you can use it with a Zend Framework DB adapter, it might look like
$sql = '<insert Maxem's query here>';
$result = $db->fetchAll($sql);
You might choose to use fetchCol() to retrieve the single result.
It sounds like you don't want to explicitly enumerate the columnn and that you want to sum all the columns (probably excluding the year column) over all the rows, with grouping by year.
Note that the method Zend_Db_Table::info(Zend_Db_Table_Abstract::COLS) will return an array containing the columns names for the underlying table. You could build your query using that array, something like the following:
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('mytable');
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
unset($fields['year']);
$select = $table->select();
$cols = array();
foreach ($fields as $field){
$cols[] = sprintf('SUM(%s)', $field);
}
$select->cols(implode(' + ', $cols));
$select->group('year');
I have not tested the specific syntax, but the core of the idea is the call to info() to get the fields dynamically.
Done in ZF rather than pure query and you don't have to write the name of the columns one by one.
(I assume you are extending Zend_Db_Table_Abstract)
If you're asking how to write
select SUM(*) from `mytable` group by `year`
This is how it is done:
public function sumOfAllFields(){
return $this->fetchAll( $this->select()->from('mytable','SUM(*)')->group('year') )->toArray();
}
Or not using Zend...
function mysql_cols($table){
$sql="SHOW COLUMNS FROM `".$table."`";
$res=mysql_query($sql);
$cols=array();
while($row=mysql_fetch_assoc($res))$cols[]=$row['Field'];
return $cols;
}
$cols=mysql_cols("mytable");
$select_sql=array();
foreach($cols as $col){
$select_sql[]="SUM(`".$col."`)";
}
$select_sql=implode('+',$select_sql);
$sql="select (".$select_sql.") from `mytable` group by `year`";