PHP result set display format - php

Hi i have a query which will result three rows of results at present. I need to show them in some way but i am not able to show like that. Can you give me some idea how i need to approach it.
I will have all the result set in an array from database.
1. client name |RO NO | channel
2. a | abc | x
3. a | abc | y
4. a | abc | z
Result set look like above but i need to display it like below in a table
1. client a
2. RO abc
3. Channel x,y,z
I don't want repeat which are common in each row. How should i do it. Can any one give me idea how to proceed...

You can use group_concat:
select `client name` as `client`, `RO NO` as `RO`, group_concat(channel) as `Channel`
from table_name
group by `client`

PHP
Use the result as array key:
$arr[$result] = true;
echo implode(',', array_keys($arr));
MySQL
Group concat with distinct:
select group_concat(distinct ...) from ...;

Related

How to count and display duplicate entries in MySQL on PHP website

I'd like to know how I can count and display duplicate rows on my PHP website. Let's assume that my website allows one to submit a name. How do I then display these names on my website? Let's say that the names in the database are:
John
Derrick
Billy
Jason
Wesley
Billy
John
Billy
I'd then like the website to display the following:
John: 2
Derrick: 1
Billy: 3
Jason: 1
Wesley: 1
How can I achieve this sort of structure?
Yes, you can make this:
select name, count(*) from your_table group by name
And that would return something like this:
name | count
John | 2
If you want the name and the count, you can make a concat
select concat(name, ": ", count(*)) from your_table group by name
And it would return something like this:
name
John: 2
(just one column)
<?php
$ps=$db->prepare("SELECT column_name, count(*) as nb FROM table_name GROUP BY column_name");
$ps->execute()
while($data=$ps->fetch()){
echo $data['column_name'].':'.$data['nb'].'<br/>';
}
?>
$db is the connection instance

SQL finding specific character in table

I have a table like this
d_id | d_name | d_desc | sid
1 |flu | .... |4,13,19
Where sid is VARCHAR. What i want to do is when enter 4 or 13 or 19, it will display flu. However my query only works when user select all those value. Here is my query
SELECT * FROM diseases where sid LIKE '%sid1++%'
From above query, I work with PHP and use for loop to put the sid value inside LIKE value. So there I just put sid++ to keep it simple. My query only works when all of the value is present. If let say user select 4 and 19 which will be '%4,19%' then it display nothing. Thanks all.
If you must do what you ask for, you can try to use FIND_IN_SET().
SELECT d_id, d_name, d_description
FROM diseases
WHERE FIND_IN_SET(13,sid)<>0
But this query will not be sargable, so it will be outrageously slow if your table contains more than a few dozen rows. And the ICD10 list of disease codes contains almost 92,000 rows. You don't want your patient to die or get well before you finish looking up her disease. :-)
So, you should create a separate table. Let's call it diseases_sid.
It will contain two columns. For your example the contents will be
d_id sid
1 4
1 13
1 19
If you want to find a row from your diseases table by sid, do this.
SELECT d.d_id, d.d_name, d.d_description
FROM diseases d
JOIN diseases_sid ds ON d.d_id = ds.d_id
WHERE ds.sid = 13
That's what my colleagues are talking about in the comments when they mention normalization.

PHP MYSQLI Count Row Correct

Table
Hello i try to finds all hashtags with name #c3 and mysqli query show me: 3 rows but correct is 2 rows with #c3 ??? where is problem ? I want to show me 2Rows !
$sql_query = mysqli_query($Connection, "SELECT * FROM my_table WHERE hashtag LIKE '%#c3%'");
echo mysqli_num_rows($sql_query);
To answer this and as left in comments (by myself)
Use '%#c3' by removing the last %
Using LIKE, the % wildcard does the following and a few examples:
%XXX% - Matches anything before and after XXX
%XXX - Matches anything before XXX
XXX% - Matches anything after XXX.
References:
http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
http://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
http://www.tutorialspoint.com/mysql/mysql-like-clause.htm
Plus, should there be any user input, consider using a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
It will help against a potential SQL injection.
https://en.wikipedia.org/wiki/SQL_injection
Hi Your query is wrong try to use this
SELECT * from my_table WHERE FIND_IN_SET('#c3', hashtag);
FIND_IN_SET returns the position of a string if it is present (as a substring) within a list of strings. The string list itself is a string contains substrings separated by ‘,’ (comma) character.
for more info read http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php
You can use FIND_IN_SET
SELECT * FROM my_table WHERE FIND_IN_SET('#c3',hashtag)
See docs here and example here
Split the table into 2 tables:
post: id | text | date
1
2
3
post_hashtag: post_id | hashtag
1 #c1
1 #c3
2 #c3
3 #c3blabla
Then your query becomes:
SELECT post.*,post_hashtag.hashtag FROM post JOIN post_hashtag ON post.id=post_hashtag.post_id WHERE hashtag='#c3#';
The act of splitting the table is called normalizing and you need to do this because your tables are not in any normal form which makes them not relational which defeats the purpose of storing them in a relational database. Check https://en.wikipedia.org/wiki/First_normal_form for more information.
Looking at your table, I would suggest that you break up your tables to have a many to many link for hashtag. That way you can search for all records that have a matching hashtag.
data table
+----+------+------+
| id | text | date |
+----+------+------+
hash table
+----+------+
| id | hash |
+----+------+
link table
+---------+---------+
| data_id | hash_id |
+---------+---------+
This would then allow you to use an SQL statement like:
SELECT * FROM data
INNER JOIN link ON data_id = data.id
INNER JOIN hash ON hash_id = hash.id
WHERE hash = '#3';

how to use where condition from stored data in array

id | name | permission
1 | John | 1,4,3
2 | mike | 7,4,3
3 | sky | 3,2,1
this is my database
now i have fetch select query with where condition
e.g. select * from friend where permission='4'
but i m not able fetch any data so what to do ?
Please help
Select * from friend where FIND_IN_SET('4',permission);
It looks like you have multiple permissions stored together in a string.
To you, the query looks like:
select * from friend where permission='4'
That means anything containing 4.
To mysql, it sees:
select * from friend where permission= ONLY '4'
// Meaning the permissions column can ONLY CONTAIN 4.
// Also, ONLY is meant as a visual, don't use it in queries.
Try:
find_in_set('4',permission) <> 0
// This means It needs to find number 4 and can't return 0 results.
Check out these for more info:
MySQL query finding values in a comma separated string
http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php
It can be done by the following query :
select * from friend where permission like '%4%'

Select random row per distinct field value?

I have a MySQL query that results in something like this:
person | some_info
==================
bob | pphsmbf24
bob | rz72nixdy
bob | rbqqarywk
john | kif9adxxn
john | 77tp431p4
john | hx4t0e76j
john | 4yiomqv4i
alex | n25pz8z83
alex | orq9w7c24
alex | beuz1p133
etc...
(This is just a simplified example. In reality there are about 5000 rows in my results).
What I need to do is go through each person in the list (bob, john, alex, etc...) and pull out a row from their set of results. The row I pull out is sort of random but sort of also based on a loose set of conditions. It's not really important to specify the conditions here so I'll just say it's a random row for the example.
Anyways, using PHP, this solution is pretty simple. I make my query and get 5000 rows back and iterate through them pulling out my random row for each person. Easy.
However, I'm wondering if it's possible to get what I would from only a MySQL query so that I don't have to use PHP to iterate through the results and pull out my random rows.
I have a feeling it might involve a BUNCH of subselects, like one for each person, in which case that solution would be more time, resource and bandwidth intensive than my current solution.
Is there a clever query that can accomplish this all in one command?
Here is an SQLFiddle that you can play with.
To get a random value for a distinct name use
SELECT r.name,
(SELECT r1.some_info FROM test AS r1 WHERE r.name=r1.name ORDER BY rand() LIMIT 1) AS 'some_info'
FROM test AS r
GROUP BY r.name ;
Put this query as it stands in your sqlfiddle and it will work
Im using r and r1 as table alias names. This will also use a subquery to select a random some_info for the name
SQL Fiddle is here
My first response would be to use php to generate a random number:
$randId = rand($min, $max);
Then run a SQL query that only gets the record where your index equals $randID.
Here is the solution:
select person, acting from personel where id in (
select lim from
(select count(person) c, min(id) i, cast(rand()*(count(person)-1) +min(id)
as unsigned) lim from personel group by person order by i) t1
)
The table used in the example is below:
create table personel (
id int(11) not null auto_increment,
person char(16),
acting char(19),
primary key(id)
);
insert into personel (person,acting) values
('john','abd'),('john','aabd'),('john','adbd'),('john','abfd'),
('alex','ab2d'),('alex','abd3'),('alex','ab4d'),('alex','a6bd'),
('max','ab2d'),('max','abd3'),('max','ab4d'),('max','a6bd'),
('jimmy','ab2d'),('jimmy','abd3'),('jimmy','ab4d'),('jimmy','a6bd');
You can limit the number of queries, and order by "rand()" to get your desired result.
Perhaps if you tried something like this:
SELECT name, some_info
FROM test
WHERE name = 'tara'
ORDER BY rand()
LIMIT 1

Categories