I'm trying to remove duplicate results from my SQL query using PHP.
table categories:
id | name
1 | sony
2 | nintendo
table subcategories:
id | name | category_id
1 | playstation | 1
2 | playstation2 | 1
3 | wii | 2
table video_games
id | name | subcategories
1 | grand theft auto | 1,2
2 | super mario | 3
My PHP code:
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
echo $game_return['name'];
}
}
}
My code works but I have duplicate video games when there have multi subcategories.
I tried using SELECT DISTINCT * FROM video_games WHERE subcategories LIKE :request but same problem.
Any idea to remove duplicate results using SQL or PHP ?
MySql is able to solve this problem by its own means.
Use 'DISTINCT' and 'FIND_IN_SET'.
Like this:
"SELECT DISTINCT
vg.id,
vg.name,
vg.subcategories
FROM
video_games vg
WHERE
FIND_IN_SET( (SELECT id FROM subcategories WHERE category_id='".$_GET['id'])."' , vg.subcategories ) > 0 "
and also you can use array_unique at first save video game names in an array and next remove duplicate value.
.
.
.
your code
.
.
$game_query->execute();
if($game_query->rowCount() > 0) {
$fetch =array_unique($game_query->fetch());
foreach ($fetch as $key => $value){
echo $value;
}
}
test
<pre>
<?php
$arr=array("name"=>"1","name2"=>"2","name1"=>"2","name3"=>"3","name4"=>"1","name5"=>"2","name6"=>"3","name7"=>"22");
print_r($arr);
$fetch =array_unique($arr);
print_r($fetch);
foreach ($fetch as $key => $value)
echo $key."=>".$value."<br>";
?>
</pre>
You can save video game names in an array, and print it afterwards. For example:
$games = array();
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
if (!in_array($game_return['name'], $games)) {
$games[] = $game_return['name'];
}
}
}
}
//now print the games
foreach ($games as $game) {
echo $game;
}
EDIT If you want more than just 'name', you can expand $games array with $key => $value combination. For example:
. . .
while($game_return = $game_query->fetch()) {
foreach ($games as $game) {
if ($game['name'] === $game_return['name']]) {
continue 2;
}
}
$games[] = array(
'name' => $game_return['name'],
'price' => $game_return['price'],
)
}
And afterwards print it like:
foreach ($games as $game) {
echo $game['name'];
echo $game['price'];
}
Related
I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}
I have this table:
| id | related_id |
| 1 | 100 |
| 1 | 200 |
| 1 | 300 |
| 2 | 400 |
| 2 | 500 |
| 2 | 600 |
I need to retrieve serialized data as:
a:3:{i:1;s:3:"100";i:2;s:3:"200";i:3;s:3:"300";}
Query
SELECT id, related_id from mytable where id = 1;
I'm trying to get this using 'while'
$result = $link->query($query);
$item = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if ($id == $f['id']){
$item[] = $f['related_id'];
}
print serialize($item);
break; // for test
}
SOLUTION that works for me (provided by Erwin - Thanks!)
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) {
$item[$id] = [1 => $f['related_id']];
} else {
$item[$id][] = $f['related_id'];
}
}
foreach ($item as $value) {
print serialize($value) . PHP_EOL;
}
Collect first each related_id and store to id array with your while loop. Then print each using foreach.
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) { // create id array if not exist
$item[$id] = [1 => $f['related_id']]; // To start with index 1
} else {
$item[$id][] = $f['related_id']; // Push each new related_id
}
}
foreach ($item as $value) {
print serialize($value); // Print each serialized
echo '<br>'; // New line
}
What you are trying to do is something like this:
$result = $link->query($query);
$items = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if(!isset($items[$id])) {
$items[$id] = array();
}
$items[$id][] = $f['related_id'];
}
foreach($items as $item) {
print serialize($item);
}
For your serialized string, you have to work with an array with related_id in the second layer. The first layer is to save all related_id in an array with the same id.
You have 6 rows, 3 have id 1 and 3 have id 2. You are specifying that you want to use these ids as array keys so you will end up with 2 arrays, each holding 3 values.
If you want each row in its own array you do this:
while($f = $result->fetch_assoc()){
$item[] = array($f['id'] => $f['related_id']);
}
I realy need help to fix this code. Actualy I want get gcm_id from table where the user selects several category from table category. An example of what I want main point is gcm_id data
"gcm_id will show if user select category A,B,C" etc.. How do I do this in php mysql. I try FIND_IN_SET with no luck
uid | email | gcm_id | app_type | categories
1 demo#gmail.com xzxzxzxz A 2,5,6
How get gcm_id if user have been select categories id 2,5, and 6?
the code :
if (!empty($cat)) {
foreach ($cat as $key => $value) {
$wc.="FIND_IN_SET('$value',categories) > 0 OR ";
}
}
$pos = strrpos($wc, "OR");
if ($pos !== false) {
$wc = substr_replace($wc, "AND", $pos, strlen("OR"));
}
$wc.=" is_active=1";
$q = "select * from datanotif where app_type='$type' AND $wc ";
$r = mysqli_query($mysqli,$q);
$users = array();
while ($row1 = mysqli_fetch_assoc($r)) {
$users[] = $row1;
}
$ids = array();
foreach ($users as $key => $value) {
$ids[] = $value['gcm_id'];
}
I have a table containing the following records:
product_id | title | category
------------------------------------
1 | apple | mobile
2 | android | mobile
3 | dell | desktop
4 | hp | desktop
and the following query:
$sql = "SELECT product_id, title, category FROM products ORDER BY category";
$stmt = $db->prepare($sql);
$stmt->execute();
while($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $results["product_id"];
echo $results["title"];
echo $results["category"];
}
The question is how to split the results and display all records in a list sorted by category as below:
Mobile
Apple
Android
Desktop
Dell
HP
Group your records after get the result set:
$products = array();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$products[$results['category']][] = array(
'product_id' => $results['product_id'],
'title' => $results['title']
);
}
foreach ($products as $category => $productList)
{
echo $category . '<br>';
foreach ($productList as $product)
{
echo $product['title'] . '<br>';
}
echo '<hr />';
}
Use SELECT * FROM products GROUP BY category ORDER BY title
After sorting your items (ORDER BY category, title), do something like this:
$last_category = "";
while(/* get a row here */) {
if( $last_category != $row['category']) {
if( $last_category != "") echo "</ul>";
echo "<ul>";
$last_category = $row['category'];
}
echo "<li>".$row['title']."<li>";
}
if( $last_category != "") echo "</ul>";
SELECT * FROM products ORDER BY category. This is to sort using category, your example output file seems different what are you trying to do?
I have a database like this:
+----+---------------------+
| id | tags |
+----+---------------------+
| 1 | test1, test2, test3 |
| 2 | test1, test2, test3 |
| 3 | test1, test2, test3 |
| 4 | test1, test2, test3 |
| 5 | buh1, buh2, buh3 |
+----+---------------------+
Now i want to display the most popular tags from this database. I have a function, and it works with a array like this:
$tag_array = array(
'test1, test2 test, test3',
'test2, test4, test2',
'buh, buh2, buh3' );
The function:
function popularTags($tag_array) {
$p = array();
foreach($tag_array as $tags) {
$tags_arr = array_map('trim', explode(',', $tags));
foreach($tags_arr as $tag) {
$p[$tag] = array_key_exists($tag, $p) ? $p[$tag]+1 : 1;
}
}
arsort($p);
return $p;
}
This is how to display the most popular tags:
foreach(popularTags($tag_array) as $tag=>$num)
{
echo $tag, " (", $num, ")<br />";
}
This works so far, with a normal array.
Now, i want to get the tags from the Database, so i extract the values from the database and run the function like this:
$result = mysql_query("select * from DB ORDER BY date DESC");
while($row = mysql_fetch_array($result)){
$tag_array = $row["$tags"];
foreach(popularTags($tag_array) as $tag=>$num)
{
echo $tag, " (", $num, ")<br />";
}
}
This give me an error though:
Warning: Invalid argument supplied for foreach()
So my question is how to show the most popular tags from the database with this function?
Thanks
My suggestion is that you normalize your database. Then a query like this becomes trivial, as well as much better performing.
select TagID, count(*)
from EntityTag
group by TagID
order by count(*) descending
limit 5
mysql_fetch_array returns all the rows. So do this:
$rows = mysql_fetch_array($result);
foreach($rows as $row) {
$tag_array = $row["tags"]; // note removing the $
foreach(...) {
}
}
This one works for me:
$result = mysql_query("select tags from DATABASE LIMIT 20");
$tags = array();
while ($row = mysql_fetch_array($result)) {
$row_tag_array = split(",", $row[0]);
foreach ($row_tag_array as $newtag) {
asort($row_tag_array);
if (array_key_exists($newtag, $tags)) {
if ($tags[$newtag] < 200) {
$tags[$newtag] = $tags[$newtag] + 20;
}
}
else {
$tags[$newtag] = 100;
}
}
}
foreach ($tags as $tag => $size) {
echo "<a style=\"font-size: $size%;\" href=\"?t=$tag\">$tag</a> ";
}
Thank you for your help though