Setting PHP Query into a nested array - php

I am trying to use PHP to logically store all of that data in a nested associative arrays, and then whenever I loop through the data or need to reference the data I would refer to the array pointer rather than doing new queries each time.
For example:
My query is
$query = $db->query("
SELECT
c.id campaign_id,
c.campaign_title,
c.start_date campaign_start_date,
c.end_date campaign_end_date,
cat.id category_id,
cat.category_title,
n.id nominee_id,
n.title nominee_title,
u.id voter_id,
u.fullname voter_name
FROM
campaign c
LEFT JOIN categories cat ON cat.campaign_id = c.id
LEFT JOIN category_nominees cn ON cn.category_id = cat.id
LEFT JOIN nominees n ON n.id = cn.nominee_id
LEFT JOIN category_votes cv ON cv.campaign_id = c.id
AND cv.category_id = cat.id
AND cv.nominee_id = n.id
LEFT JOIN users u on u.id = cv.user_id
WHERE
c.active = 1
ORDER BY
u.fullname,
c.campaign_title,
cat.category_order,
cat.category_title,
cn.nominee_order,
n.title
") or die(mysqli_error());
and im trying to set up the nested array like
$array = array() ;
while($row = mysqli_fetch_assoc($query)) {
$array[$row['campaign_id']] = $row['campaign_id'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['campaign_start_date'] = $row['campaign_start_date'];
$array[$row['campaign_id']]['campaign_end_date'] = $row['campaign_end_date'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['category_id'] = $row['category_id'];
$array[$row['campaign_id']]['category_id']['category_title'] = $row['category_title'];
}
So whenever I point to:
$array[2][3]['category_title']
It would print the category title
Do you have any ideas? I literally been at it for months and can't figure it out.

Use the following:
while ($row = mysqli_fetch_assoc($query)) {
if (!isset($row['campaign_id'])) {
$array[$row['campaign_id']] = $row;
}
if (!isset($array[$row['campaign_id']]['categories'])) {
$array[$row['campaign_id']]['categories'] = array();
}
$array[$row['campaign_id']]['categories'][$row['category_id']] = array('category_id' => $row['category_id'], 'category_title' => $row['category_title']);
}
}
$row is already an associative array, you don't need to assign each element separately. You only need to deal specially with the category information, which has to be put into a nested associative array that I've called categories. So you would access it as
$array[0]['categories'][1]['category_title']
You can loop over all the categories with:
foreach ($array[$campaign]['categories'] as $cat) {
echo "Category ID: {$cat['category_id']} Title: {$cat['category_title']}<br>";
}

Related

Autocomplete 2 queries

I'm using autocomplete for my panel and get stuck with queries. I'm getting products from prestashop database and do the following (example with 1 query):
$return_arr = array();
if ($ps_DB_con) {
$ac_term = "%".$_GET['term']."%";
$query = "SELECT ps_product.id_product
AS id_product, ps_product.id_manufacturer
AS producent_id, ps_manufacturer.name
AS producent, ps_product_shop.price
AS cena, ps_product_shop.active
FROM ps_product
LEFT JOIN ps_product_shop ON ps_product.id_product=ps_product_shop.id_product
LEFT JOIN ps_manufacturer ON ps_product.id_manufacturer=ps_manufacturer.id_manufacturer
WHERE ps_product.id_product LIKE :term";
$result = $ps_DB_con->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$return_arr[] = array('id_product' => $row['id_product'], 'producent' => $row['producent'], 'label' => "{$row['id_product']}");
}
echo json_encode($return_arr);
I would like to put 2nd query to this and join results to return_arr[] in while loop.
Select ps_feature_value_lang.value as szerokosc from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature='17'
Select ps_feature_value_lang.value as profil from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature=18
How can I join those queries into one?

Associative array always returns only 4 result

Hi want to create a associative array for below query result :
$sql = "select s.*,di.dealsimage,
ctm.city,
l.location,
GROUP_CONCAT(DISTINCT cm.cuisine ORDER BY scr.cuisine_sequence_for_store) AS cui,
GROUP_CONCAT(DISTINCT rtm.restaurant_type ORDER BY srr.rest_type_sequence_for_store) AS restauranttype
from stores s
left join city_master ctm on s.city_id = ctm.city_id
left join locations l on s.location_id = l.location_id
left join store_cuisine_relation scr on s.store_id = scr.store_id
left join cuisine_master cm on scr.cuisine_id = cm.cuisine_id
left join store_resttype_relation srr on s.store_id = srr.store_id
left join restaurant_type_master rtm on rtm.rest_type_id = srr.rest_type_id
left join store_dealcat_relation sdr on s.store_id = sdr.store_id
left join deals_category_master dcm on dcm.deal_cat_id = sdr.deal_cat_id
left join deals_image di on di.`store_id` = s.store_id
where $condition1 s.is_active = 1 $condition2 group by (s.store_id) order by s.store_id";
//echo $sql;exit;
//echo $sql;exit;
$sqlex1 = mysqli_query($db,$sql);
$custom_count = #mysqli_num_rows($sqlex1); // it prints 28
while($result1 = mysqli_fetch_assoc($sqlex1)){
$dataArr = array_push_assoc($dataArr, 'store_id', $result1['store_id']);
$dataArr = array_push_assoc($dataArr, 'store_name', $result1['store_name']);
$dataArr = array_push_assoc($dataArr, 'store_logo', $result1['store_image_url']);
$dataArr = array_push_assoc($dataArr, 'deals_image', $result1['dealsimage']);
}
//echo count($dataArr);exit;
//echo $kl;exit;
//$result = array_merge_recursive($gpsArr,$dataArr);
function array_push_assoc($array, $key, $value){
$array[$key][] = $value;
return $array;
}
The query returns 28 result but when I try to echo the count of $dataArr it prints 4 always. What im doing wrong ? How can I achieve this ?
Thanks in advance
Becasue your function array_push_assoc() creates array with 4 keys store_id, store_name,store_logo, anddeals_image`, and each key has 28 rows
Try this:
dataArr = array();
while($result1 = mysqli_fetch_assoc($sqlex1))
{
$dataArr[] = array('store_id'=>$result1['store_id'],
'store_name'=>$result1['store_name'],
'store_logo'=>$result1['store_image_url'],
'deals_image'=>$result1['dealsimage']);
}
This will create array with 28 associative arrays
Your code should be changed to:
while($result1 = mysqli_fetch_assoc($sqlex1))
{
array_push($dataArr, array ('store_id'=> $result1['store_id'], 'store_name'=> $result1['store_name'], 'store_logo'=> $result1['store_image_url'], 'deals_image'=> $result1['dealsimage']));
}

How to run a query and fetch items in 3-dimensional array format

I've been trying to get towns from local councils and local councils from states. I was able to get local councils from state, but getting towns from local councils is a problem. It keeps telling me illegal offset. this is my code:
$querys = "select id,title from link where (parent is null or parent=0) and title is not null and category='state' and type='1' order by title";
$results = mysql_query($querys,$link) or die(mysql_error());
$counts = 0;
while($rows= mysql_fetch_array($results,MYSQL_ASSOC))
{
$state_id[] = $rows["id"];//echo $state_id[$counts]."<br>";
$state[] = $rows["title"];
$querylg = "select id,title from link where title is not null and category='lga' and type='1' and parent={$rows['id']} and parent is not null order by title";
$resultlg = mysql_query($querylg,$link) or die(mysql_error());
$countlg[$counts] = 0;
while($rowk=mysql_fetch_array($resultlg,MYSQL_ASSOC))
{
$lg_id[$counts][] = $rowk["id"];//echo $lg_id[$counts][$countlg]."<br>";
$lg_name[$counts][] = $rowk["title"];
$queryt = "select id,title from link where title is not null and category='town' and type='1' and parent={$rowk['id']} and parent is not null order by title";
$resultt=mysql_query($queryt,$link) or die(mysql_error());
$counttw[$countlg][$counts] = 0;
while($row=mysql_fetch_array($resultt,MYSQL_ASSOC))
{
$tw_id[$counts][$countlg][] = $row["id"];
$tw_name[$counts][$countlg][] = $row["title"];
$counttw[$countlg][$counts]++;
}
$countlg[$counts]++;
}
$counts++;
}
I am not quite sure exactly what you want from your code (ie, how many of the counts, etc, are just there to get your array, and how many are actually required). Could you put the actual output you want?
I would be tempted to rewrite it based on a single joined query:-
SELECT a.id AS state_id, a.title AS state_title, b.id AS lg_id, b.title AS lg_title, c.id AS town_id, c.title AS town_title
FROM link a
LEFT OUTER JOIN link b ON a.id = b.parent AND b.title IS NOT NULL AND b.category='lga' AND b.type='1'
LEFT OUTER JOIN link c ON b.id = c.parent AND b.title IS NOT NULL AND b.category='town' AND b.type='1'
WHERE (a.parent IS NULL OR a.parent=0) AND a.title IS NOT NULL AND a.category='state' AND a.type='1'
ORDER BY a.title, b.title, c.title

Set variable from alias in SQL query

I have a simple JOIN query:
$lstCheck = $dbWHMCS->query('SELECT * FROM tblmonitorports mp
INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon
INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
INNER JOIN tblclients cl ON cl.id = ho.userid');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['ho.id'];
$clientid = $data['cl.id'];
}
My problem is that I have an "id" column in both the tblhosting and tblclients tables, so my variables both have the same id. I tried to set it using an alias in the example above (ho. and cl.) but it doesn't work. How can I do this in the example above?
Thank you!
How about this? (a bit rusty on php details, but this should do it):
$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid FROM tblmonitorports mp
INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon
INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
INNER JOIN tblclients cl ON cl.id = ho.userid');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hid'];
$clientid = $data['cid'];
}
You are selecting the records, with a wild card *, so you can't select the fields like that.
As per your query h.hst_serverid & ho.userid have the exact same value as you want. SO simply do this
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hst_serverid'];
$clientid = $data['userid'];
}
However, selecting specific rows might sound better too
$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid, ....');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hid'];
$clientid = $data['cid'];
}

Join MySQL Table then filter result as column name

here is my code i am using to fetch mysql result from 4 different tables
SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id;
Here is screen shot of my fetch result
http://i40.tinypic.com/2v1w0ib.png
Now what i need is to create a HTML Tables for each 'CourseTitle' in database.
Using SQL statement and PHP Code i can get result for first query but i need a second query to split table foreach 'CourseTitle'
/* connect to the db */
$connection = mysql_connect('localhost','root','123');
mysql_select_db('alhudapk',$connection);
/* show tables */
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$table = $tableName[0];
echo '<h3>',$table,'</h3>';
$result2 = mysql_query('SELECT '.$table . 'AS' .$table);
if(mysql_num_rows($result2)) {
Please guide me to build a correct and better code
What I would do is put the database results into a big array structure with the data arranged in the same sort of order it should be printed out. This makes maintaining the code a bit easier.
// run the query as you did in the question
$courses = array();
// use mysql_fetch_assoc as it makes the code clearer
while($row = mysql_fetch_assoc($result)) {
$ct = $row['CourseTitle'];
// Found a new Course Title? If so create an array to put the data rows in
if(!isset($courses[$ct]))
$courses[$ct] = array();
// add this row to the end of its course array
$courses[$ct][] = $row;
}
// now print the results out
foreach($courses as $title =>$course) {
echo "<h3>$title</h3>";
echo "<table>";
foreach($course as $line) {
echo "<tr><td>" . $line['TopicTitle'] . "</td><td>"
. $line['LessonTitle'] . "</td></tr>";
echo "</table>";
}
The code above is only printing out the first 2 columns
, but if you can get it to work you should be able to add the rest quite easily.
add:
GROUP BY c.title
to the end of your SQL statement.

Categories