Multidimensional array output - php

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)']));
}
}

Related

php if else statement: display data if there are results from either 2 functions

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';
}
?>

How to Get another value in another table using a dynamic call

I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.

mysqli query make array out of names

pretty sure this is something easy but i cant figure it out, basicly making a easy query like this:
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
the above query should get all the names out of the database, now i want it to be put into array like this:
$competitors = array(
'Paul A.M. Dirac',
'Hans Christian Oersted',
'Murray Gell-Mann',
'Marie Curie',
'Neils Bohr',
'Richard P. Feynman',
'Max Planck');
how do i get the result from my query into a array like the above on?
$competitors = array();
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
if($result->num_rows > 0)
{
while($rs = $result->fetch_assoc())
{
$competitors[]=$rs['name'];
}
}
echo "<pre />";
print_r($competitors);

Getting each variable from an array

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.

Is it possible to combine these 3 mySQL queries?

I know the $downloadfile - and I want the $user_id. By trial and error I found that this does what I want. But it's 3 separate queries and 3 while loops. I have a feeling there is a better way. And yes, I only have a very little idea about what I'm doing :)
$result = pod_query("SELECT ID FROM wp_posts WHERE guid LIKE '%/$downloadfile'");
while ($row = mysql_fetch_assoc($result)) {
$attachment = $row['ID']; }
$result = pod_query("SELECT pod_id FROM wp_pods_rel WHERE tbl_row_id = '$attachment'");
while ($row = mysql_fetch_assoc($result)) {
$pod_id = $row['pod_id']; }
$result = pod_query("SELECT tbl_row_id FROM wp_pods_rel WHERE tbl_row_id = '$pod_id' AND field_id = '28'");
while ($row = mysql_fetch_assoc($result)) {
$user_id = $row['tbl_row_id']; }
Assuming I am understanding your queries correctly, this should work:
SELECT wp.ID, wpr.pod_id, wpr.tbl_row_id
FROM wp_pods_rel AS wpr
JOIN wp_posts AS wp
ON wp.ID = wpr.tbl_row_id
WHERE wpr.field_id = '28'
AND wp.guid LIKE '%/$downloadfile'
SELECT wp_posts.ID, wp_pods_rel.pod_id, wp_pods_rel.tbl_row_id
FROM wp_posts
JOIN wp_pods_rel ON wp_posts.ID = wp_pods_rel.tbl_row_id
WHERE wp_posts.guid LIKE '%/$downloadfile' AND wp_pods_rel.field_id = '28'

Categories