Select unique text from an array - php

I am having a problem selecting the unique text from database.
This is for a movie database, Let's assume I have 2 movies in the database.
1st movie is in category: Drama, Romance, War
2nd movie is in category: Drama, Thriller
What I need, is to return an array wich will display me: Drama, Romance, War, Thriller.
My current query to mysql is the following:
$query = 'SELECT genres FROM imdb WHERE actors LIKE "%%'.$name.'%"';
In an while loop I use "foreach", like this:
foreach(explode(', ', $TMPL['genres']) as $v)
$TMPL['genre'] .= '<option value="'.urlencode($v).'">'.($v).'</option>';
This is returning me all the values, including the duplicated one, like this: Drama, Romance, WarDrama,Thriller
Any clue how to sort this out?

$query = 'SELECT DISTINCT genres FROM imdb WHERE actors LIKE "%%'.$name.'%"';
would do it

just use the array_unique function on that array of your with duplicate values!
$unique_values = array_unique($TMPL['genre']);

use DISTINCT
$query = 'SELECT DISTINCT genres FROM imdb WHERE actors LIKE "%%'.$name.'%"';

So you have a column with a delimited list of genres?
Loop through every row in your query and explode the genres, add every genre to a master array and then use array_unique()
If i understand you correctly you wont be able to do it (easily) with MySQL as you haven't normalised your database properly.

Related

Simple Array Sorting

I've read a million complicated questions on sorting arrays. I have something super simple, but I'm just not able to wrap my head around it.
I have a table in my db that has scores for games. The column labels are team1_score and team_2 score. I realize that if all the scores were in one column, I could sort them with my SQL query, but they're not.
I need to know how to fetch the results from those columns, and sort them highest to lowest and ideally assign those to variables such as $first_place and $second_place
I'm sorry I'm a noob and I've done a lot of research before coming on here, so please be gentle.
So, I have something like this...
My program keeps track of scores at a kids camp and there are multiple camps. Each row has id, camp_name, camp_logo and then goes into team1_name, team1_logo, team1_score and so on through 10 teams. Ideally, I'd like to have the query fetch all those scores, and output them in Descending order with something like First Place: xxx points (team name) (team logo)
I can sort the scores with this...
$query = "SELECT team1_score, team2_score FROM camps ";
$scores = mysqli_query($connection,$query);
$scores_array = mysqli_fetch_assoc($scores);
arsort($scores_array);
foreach ($scores_array as $key => $value) {
echo "score - [" . $key . "] = " . $value . "\n";
}
but I don't know how to associate the name and logo with those keys. I hope that makes sense.
This can actually done by SQL. You could use greatest and least to get the top and bottom scores, respectively, and then also sort by them:
SELECT GREATEST(team1_score, team2_score),
LEAST(team1_score, team2_score)
FROM camps
ORDER BY 1 DESC, 2 DESC

How to go over comma separted values in MYSQL

My database structure is like this:
Movie Name GenreID**
Movie1 1,2,3
Movie2 2,4
Movie3 4,5,16
I need to select a Movie name based on the Genre ID the user selected which I put inside the genreIDArray[]
Let's say for example the genreIDArray has values: $genreIDArray = ['1','2','3'];
My current query method is the ff:
Here I prepared each ID into parts so the result won't become genreID LIKE (%1,2,3%) because I checked this doesn't work.
So I did this separation loop:
$queryParts = array();
foreach($genresIDArray as $genreID) {
$queryParts[] = "'%".$genreID."%'";
}
After the separation loop I put together the final query:
$genreString = implode(" OR genreID LIKE ",$queryParts);
$genreQuery = " SELECT * FROM movies WHERE (genreID LIKE {$genreString}) ";
gave me this final query output:
SELECT * FROM movies WHERE (genreID LIKE '%1%' OR genreID LIKE '%2%' OR genreID LIKE '%3%')
This actually works, but apparently not that efficient because genreID 11,12,13 and so on that start with 1 is also selected. I think I'm missing the MYSQL LIKE logic here. I've tried '%$genreID' which means to select the starting or first number/letter of a table data, but that's still the same thing, $genreID% doesn't and would not work because this only means genreid ENDING letters/number will be selected.
I hope I spelled that out clear enough. I'm in a bind here. Please help.
Thank you so much.
There is a very cool function for that. You can use FIND_IN_SET.
SELECT * FROM test WHERE FIND_IN_SET(1,colors)
But if its possible you should avoid such structures in your database and normalize your database.

Query find value in comma seperated list mysql

in my script a "restaurant" can have multiple locations so, i made a column in the restaurant table containing a coma seperated list with locations.
Now i want to make a msql query that checks if the id can be fount is this column (comma seperated list) and if so then select it. i came up with this
SELECT restaurant_id,restaurant_name
FROM restaurant WHERE ('.$locIdList.') IN (locationRes)
ORDER BY restaurant_name ASC'
It does work... but i have some restaurants where I added location 16 and 17 so (16,17) now when i do this query for location 16 it shows the restaurant but when i dot this for location 17 it does not... but the whole point was to get the multi values from the comma seperated list.
So how to do this ?
You can use PHP to generate the query for each comma-delimited value. i.e., run a PHP loop on comma-delimited comparison string, convert it into individual items and compare each item through LIKE Operator and an IN () function.
SELECT restaurant_id,restaurant_name
FROM restaurant WHERE ('16') IN (locationRes)
OR
FROM restaurant WHERE ('17') IN (locationRes)
ORDER BY restaurant_name ASC'
The best solution would be to create a relation table that implements the many-to-many relationship between restaurants and locations. Then you can use a solution like How to return rows that have the same column values in MySql to find all the restaurants that are in all locations.
To search for a value in a comma-separated list, you use FIND_IN_SET. But this can only search for one value at a time. If you want to find restaurants that are in all locations, you need to combine multiple calls:
$locArray = explode(',', $locIdList);
$locQuery = implode(' AND ', array_map(function($loc) { return "FIND_IN_SET($loc, locationRes)"; }, $locArray));
$query = "SELECT restaurant_id,restaurant_name
FROM restaurant
WHERE $locQuery
ORDER BY restaurant_name ASC";
If you want to find restaurants that are in any of the locations instead of all locations, change AND to OR.
You should avoid putting multiple values inside a single column.
Instead, it's recommended to create another table locations(location_id, col1, col2, restaurant_id), while the restaurant_id field references to the primary key in table restaurant.
If you have a comma separated list you are pulling from a database, you could use PHP to separate the list and create an array of each item.
$result_of_sql = "restaurant 1, restaurant 2, restaurant 3, restaurant 4, restaurant 5, restaurant 6";
$restaurants = explode(',', $result_of_sql);
echo '<ul>';
foreach ($restaurants as $restaurant) {
echo '<li>' . trim($restaurant) . '</li>';
}
echo '</ul>';
What happens here is first, you pull out all of you restaurants (the comma separated list). Then you use explode to take away the commas and create an array. Then you use the foreach loop to echo the entire array out. trim is just to clean everything up by removing whitespace you might have before and after the restaurant name.

SQLite3 duplicates

I'm having difficulties with SQLite3. The table is as follow:
id|name
11|test1
31|test1
51|test1
13|test2
17|test2
..|..
I need to get only one name and all id's for that name, like this:
test1|array(11,31,51)
test2|array(13,17)
...
How can I do it with PHP and SQLite3? Thank you.
use group_concat
SELECT
name,
group_concat(id) AS ids
FROM Table
GROUP BY name
will return something like
test1|11,31,51
test2|13,17
and then you can just explode the ids, to get them as array.
$ids_array = explode(",",$ids);

mysql results sort by array

I think I don't understand how 'sort' works, so please don't judge me. I really searched all day long.
I have a movies table with actors column. A column it's named "actors". The actors are links separated by space " ". The order of the links it's very important.
I explode the links into an array which looks like [0]-> link0, [1]->link1, ...
I have the actors table where every actor also has it's movies links. I don't want to make 20 different sql searches so I made a variable with all the links I want, like this ( WHERE actor_link = link1 OR actor_link = link2 OR .. )
The problem is this. The search will probably find first the link7, and so my sorting it's gone. What can I do to keep that order from the movies table. I want to display the actors by popularity in the movie, not the order of my database.
Can you give me another method to search the actors without making 'x' sql searches and still keeping the order?
$actors[] = explode(" ", $row['actors_link']);
$x=0;
$actors2 = '';
while ($actors[0][$x]) {
$actors2 = $actors2 . "`link_imdb_actor` = " . "'".$actors[0][$x]."' OR ";
$x++;
}
$actors2 = substr($actors2, 0, -3);
$sql = "SELECT * FROM `actors` WHERE $actors2";
$sql_result = mysql_query($sql) or die(" ");
while ($row3 = mysql_fetch_array($sql_result)) {
echo $row3['link_imdb_actor'];
}
So, the movie Hotel Transylvania has Adam Sandler, Andy Samberg and Selena Gomez. My search shows Selena Gomez, Andy Samberg, Adam Sandler because this is the order from my database. How can I sort the sql results by the order of the actors array? Thank you!
To expand on Arjan's comment, if you want to be able to actually use the actor data (e.g. search with it) I would recommend at least two more tables. One called actors with the fields actorID, firstName, and lastName. The other table would be castings with the fields castingID, actorID, movieID, and castingOrder.
Each castingID will then link an actor to a movie - this would make for easy searches of every movie a particular actor has been in or every actor in a particular movie.
The castingOrder field can be used to maintain the order you want.
I need your existing code to really get the gist of what's going on.
I will make one suggestion in your query. Instead of saying WHERE actor_link = a OR actor_link = b OR actor_link = c do this instead:
WHERE actor_link IN (link1, link2, link3)

Categories