SQLite3 duplicates - php

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);

Related

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.

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

Count duplicates WHERE id=?

I want to be able to SELECT opponents id from a db table WHERE id=$currplayer.
My DB table is like this:
fk_player
fk_opponent
If I do like this:
SELECT fk_opponent
, COUNT(fk_opponent) AS oplay
FROM nf_newversus
GROUP BY fk_opponent
It does the thing right, but I want to be able to sort this so it is only the ones where fk_player = $currplayer... I have tried to insert a WHERE fk_player = $currplayer but that is not right...
Any help is appreciated.
SELECT fk_opponent
, COUNT(fk_opponent) AS oplay
FROM nf_newversus
WHERE fk_player = '$currplayer'
GROUP BY fk_opponent
This should be correct according to your description:
SELECT fk_opponent, COUNT(*) AS oplay
FROM nf_newversus
WHERE fk_player='$currplayer'
GROUP BY fk_opponent
If your table allows multiple player1 vs player2 (i.e. no UNIQUE(fk_player, fk_opponent) index), that should work just fine, but assuming you store matches in both ways.

Mysql Query In codeigniter

This is my mysql query
$acountry = 1;
$this->db->where_in('varcountry', $acountry);
$val = $this->db->get('tblagencies')->result();
In database table the varcountry filed is stored like this 1,2,3,4 its type is varchar.Each row in table have multiple countries that is the reason to use varchar datatype.
Here i want to select table rows which have $acountry value in the filed varcountry.
How can i do that?The above code is it correct?
You have choosen a wrong data type for storing a comma separated value 1,2,3,4 into varchar,
you should chose a data-type of set, or normalize into a separate table, like :-
create table country (id, name ...);
create table agencies_country ( agency_id, country_id);
insert into agencies_country (agency_id, country_id)
values (x,1), (x,2), (x,3), (x,4);
// meaning 1,2,3,4 = 4 rows
// grabbing result using inner join
Using set is easier, but common practice is to normalize the data (which require some understanding).
I don't like the active record in codeigniter,
is easy to use (not doubt with this),
but it dis-allowed lost of flexibility
Personally I like the construct my own query,
provided you have the understanding of the table schema (which you have to anyway)
use this query..
$search_field = array('varcountry'=>$acountry)
$result = $this->db->get_where('tblagencies' , $search_field );
but in codeignator you can use your own queries like
$sql = "select * from tblagencies where varcountry like '%acountry%'";
$result = $this->db->query($sql);

Select unique text from an array

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.

Categories