Combine two rows into one string - php

i have dynamic database, and i want to search in this table
FieldID | Content | TypeID
--------------------------
ABC-123 | jon | 1
EFG-456 | doe | 1
HIJ-789 | man | 1
So my SELECT query looks something like this:
SELECT
GROUP_CONCAT(fieldsContent.Content SEPARATOR '|*|') AS Content,
GROUP_CONCAT(fieldsContent.FieldID SEPARATOR '|*|') AS FieldID,
FROM (`customers`)
LEFT OUTER JOIN `fieldsContent` ON `fieldsContent`.`TypeID` = `customers`.`ID`
GROUP BY `fieldsContent`.`TypeID`
ORDER BY `customers`.`Created` DESC
And the result looks like this
Array
(
[0] => stdClass Object
(
[Content] => jon|*|doe|*|man
[FieldID] => ABC-123|*|EFG-456|*|HIJ-789
)
)
And when i'm adding HAVING and searching only for jon, it will return me the result
HAVING Content LIKE "%jon%"
But, when i'm trying to search jon doe it will return empty result
HAVING Content LIKE "%jon doe%"
Because jon doe don't exists in the string, only jon|*|doe
So how can i combine these two rows to one string without the SEPARATOR for me the search in them jon doe ?
BUT!! keep in mind that i need to obtain the SEPARATOR because i need to combine the data to be used in php.
ex:
$field = explode('|*|',$data->FieldID);
$content = explode('|*|',$data->Content);
foreach($field as $k => $FieldID){
switch($FieldID){
case 'ABC-123':
$res['first_name'] = $content[$k];
break;
case 'EFG-456':
$res['last_name'] = $content[$k];
break;
case 'HIJ-789':
$res['gender'] = $content[$k];
break;
}
}
Any ideas will be appreciated :)

TRY THIS #1
HAVING Content LIKE "%jon%doe%"
TRY THIS #2
HAVING Content LIKE "%jon" AND Content LIKE "%doe%"
TRY THIS #3
HAVING REPLACE(Content,'|*|',' ') LIKE "%jon doe%"
GIVE IT A TRY !!! :-)

Use:-
HAVING Content LIKE "%jon%" AND Content LIKE "%doe%"

Related

Codeigniter - How to select row id's of matching date column in query

I am trying to write a query that outputs the shiftId's into an array.
I have a table that looks like this.
+---------+----------+-------+
| shiftId | endTime | shift |
+---------+----------+-------+
| 1 | 03/03/19 | 1 |
| 2 | 03/03/19 | 2 |
| 3 | 03/01/19 | 1 |
| 4 | 03/01/19 | 2 |
+---------+----------+-------+
I want to return the shiftId of each date with the largest shift, and not sure how to go about.
I want my array to look like below, based on above table.
Array
(
[0] => 2
[1] => 4
)
I have tried to group_by date and then select_max of each shift but don't think I'm on the correct path. Any help would be appreciated.
I want to select shiftId foreach date where shift # is the largest.
You were on the right path!
Either use (this shows the SQL more clearly):
$query = $this->db->query('SELECT max(shiftId) shiftId FROM yourtable GROUP BY endTime')->result_array();
Or (if you want to use CI's query builder):
$query = $this->db->select_max('shiftId')->group_by('endTime')->get('yourtable')->result_array();
Both of these group the table by endTime, and then return the maximum shiftId for each group of identical endTimes. Both give an array that looks like this:
Array
(
[0] => Array
(
[shiftId] => 2
)
[1] => Array
(
[shiftId] => 4
)
)
To get rid of the shiftId index in the result and get the exact array structure from your OP, use:
array_column($query, 'shiftId');
Edit
If you want to get the shiftId for each endTime + MAX(shift) combination, use this:
SELECT shiftId FROM yourtable
WHERE CONCAT(endTime, "-", shift) IN (
SELECT CONCAT(endTime, "-", MAX(shift)) FROM yourtable GROUP BY endTime
)
The inner query (after IN) does more or less the same as the previous query: it groups the records in the table by endTime, then gets the maximum shift for each group of identical endTimes, and here it concatenates this with the endTime and a dash.
You need to concatenate endTime with MAX(shift) here, because MAX(shift) alone is not unique in the table (there's more than one shift with number 2, for example), and neither is endTime.
The outer query (SELECT shiftId...) then finds the matching shiftId for each endTime + MAX(shift) combination and returns that.
You need to use two (nested) queries for this, because the inner one uses grouping and the outer one doesn't, and you're not allowed to mix those two types in one query.
Note: CONCAT only works in MySQL, if you're using a different database type, you might have to look up what concatenation syntax it uses (could be + or || for example).
In CI:
$query = $this->db->query('SELECT shiftId FROM yourtable
WHERE CONCAT(endTime, "-", shift) IN (SELECT CONCAT(endTime, "-", MAX(shift)) FROM yourtable GROUP BY endTime)')->result_array();

How to do query to locate specific text in string and grab section next to it?

Trying to understand LEFT and LOCATE with mysql to help me process a string
I have text that contains a bunch of data and within it is
street_num="9716", street_name=
I need to extract just the street num
so I was trying to do
SELECT LEFT( newdata, LOCATE( 'street_name=', 'newdata' ) )
FROM `uploadTracker`
WHERE `type` =0
in that example I would like it to return 9716
In situations like this function SUBSTRING_INDEX() becomes very handy
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(newdata, 'street_num="', -1), '"', 1) street_num
FROM uploadTracker
WHERE type = 0
Output:
| STREET_NUM |
|------------|
| 9716 |
Here is SQLFiddle demo

PHP PDO fetchAll, PDO::FETCH_CLASS and joins

I have a problem in the following code:
$query = 'SELECT user.id as id, pet.name as name FROM user
LEFT JOIN pet on pet.user_id = user.id
WHERE user.id = 15';
$result = $pdo->query($query);
This code will produce something similar to this:
***************
| id | name |
***************
| 1 | Mikey |
***************
| 1 | Stewie |
***************
| 1 | Jessy |
***************
Now, I'd like to use PDO::FETCH_CLASS to get an object. However, this method, at least to me, works fine only with simple SELECT statements. When you have a join statement, then it will fetch everything in a single class. In other words:
$user = $result->fetchAll(PDO::FETCH_CLASS, 'User');
echo $user->name; // this will print the pet name (which is weird)
Therefore, I'd like to have something similar:
$pets = $user->pets; // an array holding Pet Objects
foreach ($pets as $pet)
echo $pet->name . "-";
which will produce:
Mikey - Stewie - Jessy -
How can I achieve this?
You can't rely on PDO to do the job for you. PDO has no way to know where the dataset columns come from and it obviously can't figure out where you want to dump the data.
The simplest answer is that you have to write your own code. Fetch rows as arrays and populate your classes with it as it's always been done ;-)
The technique you describe is ORM (Object-relational mapping). There're some third-party libraries that implement it, such as Doctrine or Propel.
I open sourced a very small function that will transform joined results into a hierarchy. This avoids using heavy ORMs if you just need this small feature. https://github.com/afilina/nestedsql
You'd give it a statement like this:
SELECT album.id AS albums__id, photo.id AS albums__photos__id
FROM album
LEFT JOIN photo ON photo.album_id = album.id;
and it will produce something this:
stdClass Object
(
[albums] => Array
(
[1] => stdClass Object
(
[id] => 1
[photos] => Array
(
[1] => stdClass Object
(
[id] => 1
)
)
)
)
)
Optionally, you can replace stdClass by your own classes.

Iterative appending of array with arrays from sql results

am new here, but have enjoyed reading others' questions and answers. I'm fairly new to PHP and am working on a project - basic table look-ups in MySQL, etc.
What I want to end up with is an array of arrays, the form of which is shown below with condiments (not my actual project). The content is coming from two different tables. For each of the condiment names (from table 1) I look up in table 2 the types of condiments, linked by ID. The searching and grabbing stuff is fine, but I'm having trouble looping and building my final $Condiments array.
The first part of the loop, I grab the condiment name from the $row and append it to the array. But I need each of these condiment names to be an empty array to put something in, in the next step. I've looked around but couldn't find a good way to iteratively append new placeholder arrays into an array. Is there an elegant solution? Some cool function I'm not taking advantage of? Thanks!
// SQL search for condiment words, blah blah, leading to...
$rowsnumber = mysql_num_rows($result);
for ($j = 0 ; $j < $rowsnumber ; ++$j)
{
$row = mysql_fetch_row($result); // $row is an array featuring a condiment name and other stuff.
$Condiments[] = $row[1]; // condiment name goes in array.
$CondimentType = searchTable2($row[0]);
// using the condiment name's ID, I look up its matching types via a function.
// $CondimentType is now an array of IDs and types from Table2 that I want to append to the condiment name I just added above.
$Condiments[$row[1]] = $CondimentType;
// I repeat the process for the next name
}
// Final desired result...
$Condiments=
Array
(
[Pickles] => Array
(
[34] => Dill
[23] => Butter
)
[Mustard] => Array
(
[22] => Hot
)
[Relish] => Array
(
[3] => Pickle
)
)
so like i said , you need to use join to perform the needed task.
you can find more explanation here about joins
http://dev.mysql.com/doc/refman/5.0/en/join.html
in your case , this query should do the job
select t1.word,t3.word
from table1 as t1 join table2 as t2 on t1.id =t2.id
left join table1 as t3 on t3.id = t2.linkid
i ran the query in my machine and these are the results
+---------+--------+
| word | word |
+---------+--------+
| Pickles | Dill |
| Pickles | Butter |
| Mustard | Hot |
| Relish | Pickle |
+---------+--------+
so instead of looping through each row, just perform a join and get the results. in php then you can do the needed format of the array.
hopefully this will help you

Select rows where column text contains value of an array

I'm building a search function in php/mysql and I'm looking for the right MySql function. My table sort of looks like this:
id | text
--------------------------------------
1 | I like pony's.
2 | Do you like fish?
3 | We like fishes!
I want to search the column 'text' for one of the exact values of an array, for example:
$search_array = array('fish','dogs','cat','panda');
I'm looking for the right MySql function to return only the second row (with the current array). The array can contain hundreds of values.
I have 6000+ rows, growing everyday with +/- 400. I've tried REGEXP but with a large array, it took about 10 seconds before it returned the corresponding rows.
Please help, I'm fighting with this for almost 3 full days now... Thanks in advance!
If the search array is constant, or changes infrequently, I recommend having another two tables, 'tags' and 'tags-text'.
For example, the row with id 2 in your example contains fish, since fish is in our 'tags' table a new record will be placed in a 'tags-text' table. When you are searching with your array, you can search if one of the array components is in the 'tags-text' table, and join the 'text' table and return the text and id and do whatever you need.
Structure of other tables:
'tags' table
id | tags
--------------------------------------
1 | fish
2 | dogs
3 | cats
'tags-text' table
text-id | tags-id
--------------------------------------
2 | 1
Does this help/make sense
Ok I think I've found the easiest solution: let PHP create the mysql query and solve it with WHERE LIKE.
$search_array = array('fish','dogs','cat','panda');
$string = '';
foreach($search_array as $term) {
$string = $string."text LIKE '%".$term."%' AND ";
}
The result of the foreach loop is:
"text LIKE '%fish%' AND LIKE '%dogs%' AND LIKE '%cat%' AND LIKE '%panda%' AND "
Now lets remove the tail of that string and write the query:
$string = substr($string, 0, -5); // removing " AND " at the end of the string
$query = "SELECT * FROM table WHERE $string";
$results = mysql_query($query);
Thanks for the other answers anyway :)
Ok, maybe you should try mixing mysql and php a bit.
Here is the pseudo-code
select 100-1000 rows at one time from db
use strpos to check each element in your array against the text column
if element found
store it
if 2 elements found break the loop
else
continue
Something like this maybe ...
$search_term = implode(",",$search_array);
SELECT * FROM your_table WHERE text IN ($search_term)";

Categories