I am trying to retrieve tags that are associated with a society. The code below works, but it is only retrieving the first tag and not the rest in the table.
$user = $_SESSION['user'];
$society = $_SESSION['society'];
$soc_q = mysql_query("SELECT socID, creator, socName, type, datetime
FROM societies.society WHERE socName = '$society'");
$soc_row = mysql_fetch_array($soc_q, MYSQL_ASSOC);
$tag_q = mysql_query("SELECT society.socID, tagID, name
FROM societies.society
INNER JOIN societies.tags ON society.socID = tags.socID
WHERE society.socID = '$soc_row[socID]'");
$tag_row = mysql_fetch_array($tag_q, MYSQL_ASSOC);
$the_tags = $tag_row['name'];
if (!#$_SESSION['existing_tags']) {
$_SESSION['existing_tags'] = $the_tags;
}
$existing_tags = $_SESSION['existing_tags'];
$tags = explode(' ', $the_tags);
// ajax
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && #$_GET['tag']) {
$match = array();
foreach ($tags as $tag) {
if (stripos($tag, $_GET['tag']) === 0) {
$match[] = $tag;
}
}
echo json_encode($match);
exit;
You have to load tags in loop like this (get each row):
$the_tags = array();
while( $tag_row = mysql_fetch_assoc( $tag_q)){
$the_tags[] = $tag_row['name'];
}
Edit: using GROUP BY
If you are willing to play with mySQL and element grouping you may use GROUP_CONCAT (if you need only tag names):
$tag_q = mysql_query("
SELECT GROUP_CONCAT( DISTINCT tags.name SEPARATOR ', ') as `tags`
FROM societies.society
INNER JOIN societies.tags ON society.socID = tags.socID
WHERE society.socID = '$soc_row[socID]'
GROUP BY NULL");
$tag_row = mysql_fetch_array($tag_q, MYSQL_ASSOC);
$tag_names = explode( ', ', $tag_row['tags']);
The code above isn't that useful, but when you'll combine it with your first query, you'll get:
$soc_q = mysql_query("SELECT socID, creator, socName, type, datetime,
GROUP_CONCAT( DISTINCT tags.name SEPARATOR ', ') as `tags`
FROM society
LEFT JOIN societies On societies.socID = society.socID
LEFT JOIN tags ON societies.tagsID = tags.socID
WHERE socName = '$society'
GROUP_BY society.id");
$soc_row = mysql_fetch_array($soc_q, MYSQL_ASSOC);
Note: prefixing tables with database names makes your code hard to read because once you're doing that, other time not.
Related
I have written a SELECT Query to concatenate a person's name and email address. I then want to echo this string.
Here is the code:
$sqldiv = "Select concat(p1.display_name, " - ", p1.user_email) AS Contact FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
If I use this SELECT QUERY it works:
$sqldiv = "Select p1.display_name FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
The only difference is that I am using concat. If I run the SELECT Query through SQL I get the output in a single string, which I assume is correct to set $div as an array.
What am I doing wrong?
UPDATE :
i need get a all values of tags field !
MY Query :
$query = db_select('node', 'node');
$query->fields('tagsdata',array('name'));
$query->fields('node', array('nid'));
$query->leftJoin('field_data_field_tags', 'tags', 'tags.entity_id = node.nid');
$query->leftJoin('taxonomy_index', 'tagsindex', 'tagsindex.nid = tags.entity_id');
$query->leftJoin('taxonomy_term_data','tagsdata','tagsdata.tid = tags.field_tags_tid AND node.nid = tagsindex.nid');
$result = $query->execute();
while( $record = $result->fetchAssoc() ) {
$items[] = $record;
}
AND MY CODE :
//SORT
array_multisort(array_column($items, 'nid'), $items);
foreach ($items as $row) {
$hash[$row[nid]] = $row;
}
$resultfinal = ($hash);
// END SORT
foreach($resultfinal as $finalarrays)
{
$tags=$finalarrays['name'];
print_R ($tags);
}
WITH above code just return one and first value of tags, i need to print all of them !
You can use GROUP_CONCAT mysql function to get all value imploded by comma :
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
NB : sometimes you have too much string to concat so you need to increase limit before by :
db_query('SET SESSION group_concat_max_len=10000');
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
foreach($result as $nid => $tags) {
echo $nid . ' : '.$tags;
}
I'd really appreciate some help with this code as I can't get it to work properly.
I have two separate functions that both check a table in my database for data against an ID that is fetched from the page's URL. On displaying the information, I want to use an IF ELSE statement to check if there are results from either of those functions, and if there are no results, post nothing, and if there are results, post the results.
Below are my functions:
function getArtistsBySongId($id) {
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Remix` AS r ON r.remix_id = c2a.remix_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id
ORDER BY a.artist_name ASC";
$res = mysql_query($query);
$artists = Array();
$artisttoid = Array();
$songtoid = Array();
while( $row = mysql_fetch_array($res) ) {
$artist = $row[artist_name];
$credit = $row[credit_name];
$songcr = $row[song_id];
if(!array_key_exists($artist, $artists) ) {
$artists[$artist] = Array();
$artisttoid[$artist] = $row[artist_id];
$songtoid[$songcr] = $row[song_id];
}
$artists[$artist][] = $credit;
}
return array($artists, $artisttoid, $songtoid);
}
function getGroupsBySongId($id) {
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Remix` AS r ON r.remix_id = c2a.remix_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$groups = Array();
$grouptoid = Array();
$song2id = Array();
while( $row = mysql_fetch_array($res) ) {
$group = $row[group_name];
$credits = $row[credit_name];
$songcred = $row[song_id];
if(!array_key_exists($group, $groups) ) {
$groups[$group] = Array();
$grouptoid[$group] = $row[group_id];
$song2id[$songcred] = $row[song_id];
}
$groups[$group][] = $credits;
}
return array($groups, $grouptoid, $song2id);
}
At the moment I have this code:
<?php
if ((getArtistsBySongId($id) != NULL) OR (getGroupsBySongId($id) != NULL)) {
include 'songs/getsongcredits.php';
}
?>
While the code works in displaying my data, it seems to be ignoring my IF statement, and just posting what's in the include. Would someone be able to let me know the correct way to do this? Thanks in advance.
Both of your functions are returning an array regardless of the outcome of the query. Therefore you should check if the result returned from your functions are empty or not.
<?php
if (!empty(getArtistsBySongId($id)) OR !empty(getGroupsBySongId($id))) {
include 'songs/getsongcredits.php';
}
?>
Since both of your functions return arrays I would consider checking the size of the arrays returned. If you have data then the array size would be greater than 0 otherwise it would be 0.
<?php
$artistsBySongId = count(getArtistsBySongId($id));
$groupsBySongId = count(getGroupsBySongId($id));
if (($artistsBySongId != 0) || ($groupsBySongId != 0)) {
include 'songs/getsongcredits.php';
}
?>
Thanks all for taking the time to answer my question. However, neither of the codes worked in my site. A friend of mine has helped me though and it is now working. This is the code he used:
<?php
$errors = array_filter(getArtistsBySongId( $id ));
$errors1 = array_filter(getGroupsBySongId( $id ));
if (empty($errors) AND empty($errors1)) {
} else {
include 'songs/getsongcredits.php';
}
?>
if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
So I have this array data which i want to be coded somewhat like [lojas, raparacoes, valor],[nome_1, count_1, val_1],[nome_2, count_2, val_2], etc, etc...
lojas, reparacoes and valor are like headers
nome_* comes from $row['nome']
count_* comes from intval($row['COUNT( DISTINCT id_reparacao )'])
val_* comes from intval($row2['SUM(valor)'])
$data = array(array('Lojas'), array('Reparacoes'), array('Valor'));
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data=[$row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)'])];
}
}
However, with this code I'm not getting the desired output in the array, I guess the problem is the way i fill it but I don't know how to properly fill it so it gets the output I posted in the first paragraph.
PS: I don't know if it matters but for better understanding, I need this array to build a google bar chart
You can try this code.
$data = array();
$data[] = array('Lojas', 'Reparacoes', 'Valor');
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data[]=array($row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)']));
}
}