sort data when loop by a calculated column - php

someone can help me to sort this table by calculated $changepercentage please.
My table has more than 1000 records and it's uploaded by date order . I tried arsort() , SORT() when it's echo but PHP says it's not an array but a string.
I have tried mysqli_fetch_array() also but no luck.
need your kind help.
clo_prices (table)
date | name | cl_price |
2015-09-15 | AAA | 10 |
2015-09-15 | BAA | 20 |
2015-09-15 | ABA | 30 |
2015-09-16 | AAA | 86 |
2015-09-16 | BAA | 65 |
2015-09-16 | ABA | 33 |
price_list (table)
date | name | volume | last |
2015-09-15 | AAA | 6655245 | 56 |
2015-09-15 | ABA | 5666 | 65 |
2015-09-15 | AAB | 1333 | 33 |
2015-09-16 | AAA | 112365 | 56 |
2015-09-16 | ABA | 23131 | 8 |
2015-09-16 | AAB | 23330 | 12 |
2015-09-16 | ABB | 2323122 | 60 |
2015-09-16 | ACB | 21222 | 99 |
Desired Result
date | company | closing | volume | Change % |
2015-09-16 | AAA | 56 | 6655245 | 66 |
2015-09-16 | ABA | 65 | 5666 | 9.7 |
2015-09-16 | ACB | 69 | 1333 | 7 |
2015-09-16 | AAB | 33 | 112365 | 3.2 |
$queryTMG = "SELECT price_list.date, price_list.name, price_list.last, price_list.volume,
clo_prices.date, clo_prices.name, clo_prices.cl_price
FROM price_list
INNER JOIN clo_prices
ON price_list.name = clo_prices.name
WHERE price_list.date= '$dateT' AND
clo_prices.date = '$dateT'
ORDER BY cl_price DESC LIMIT 10 ";
$queryPMG = "SELECT price_list.date, price_list.name, price_list.last, price_list.volume,
clo_prices.date, clo_prices.name, clo_prices.cl_price
FROM price_list
INNER JOIN clo_prices
ON price_list.name = clo_prices.name
WHERE price_list.date= '$dateT' AND
clo_prices.date = '$dateP'
ORDER BY cl_price DESC LIMIT 10";
$resultTMG = mysqli_query($dbc, $queryTMG) or die (mysqli_error());
$resultPMG = mysqli_query($dbc, $queryPMG) or die (mysqli_error());
echo '<table cellpadding = 15 border =1>';
echo '<tr>
<th>Company</th>
<th>Closing Rs.</th>
<th>Volume</th>
<th>Change %</th>
</tr>';
while($rowTMG = mysqli_fetch_assoc($resultTMG) AND $rowPMG = mysqli_fetch_assoc($resultPMG))
{
echo '<tr> <td>'. $rowTMG['name']. '</td>';
echo '<td>'. $rowTMG['last']. '</td>';
echo '<td align = "right">'. $volumeTMG = number_format($rowTMG['volume']). '</td>';
echo '<td align = "right">'.$changeprecentage =
number_format((( $rowTMG['cl_price'] - $rowPMG['cl_price'] ) /
$rowTMG['cl_price']), 2, '.', '' ). '</td> </tr>';
}
echo '</table>';

I probably have not quite understood yet how you compute your percentages, because using the data given I get different results, see my fiddle here
SELECT p.date, p.name, p.last, p.volume,
d.cl_price+0 prevprice,
c.cl_price+0 currprice,
100*(c.cl_price-d.cl_price)/c.cl_price perc_change
FROM price_list p
INNER JOIN clo_prices c ON p.name = c.name -- current prices
AND p.date = c.date
INNER JOIN clo_prices d ON p.name = d.name -- previous prices
AND '2015-09-15' = d.date
WHERE p.date= '2015-09-16'
ORDER BY perc_change desc
This solution is so far only a MySQL select statement, since everything can be done in a single query. You will probably have to sort out some of the logic or the input data.
For the purpose of the example I assumed that $dateT is '2015-09-16' and $dateP is '2015-09-15'.

Related

Query SUM for two fields in two different tables PHP

I am having a problem generating the result I need. I want to sum the other table gg_hp base on gg_id
+--------------+----------+-------+------------+
| sg_name | sg_grade | gg_id | subject_id |
+--------------+----------+-------+------------+
| Quiz 1 | 20 | 14 | 68 |
| Midterm Exam | 50 | 15 | 68 |
| Quiz 2 | 50 | 14 | 68 |
+-------+--------------+----------+-------+----+
tbl_gradesubcateg
+-------+--------------+------------+------------+------------+------------+-------+
| gg_id | categname | percentage | gradecount | teacher_id | subject_id | gg_hp |
+-------+--------------+------------+------------+------------+------------+-------+
| 14 | Quiz | 10 | NULL | 4 | 68 | 0 |
| 15 | Midterm Exam | 20 | NULL | 4 | 68 | 0 |
+-------+--------------+------------+------------+------------+------------+-------+
This is my expected output
+-------+--------------+------------+------------+------------+------------+-------+
| gg_id | categname | percentage | gradecount | teacher_id | subject_id | gg_hp |
+-------+--------------+------------+------------+------------+------------+-------+
| 14 | Quiz | 10 | NULL | 4 | 68 | 70 |
| 15 | Midterm Exam | 20 | NULL | 4 | 68 | 50 |
+-------+--------------+------------+------------+------------+------------+-------+
This is the query I made but.. Im not getting accurate result.
$querycount = "SELECT * FROM tbl_gradesubcateg order by gg_id asc ";
$query_run = mysqli_query($con,$querycount);
$sums= 0;
$ctr = 0;
$id1 = "";
while ($num = mysqli_fetch_assoc ($query_run)) {
$sums += $num['sg_grade'];
$id= $num['gg_id'];
if($id == $id1)
{
$queryhp = mysqli_query($con,"UPDATE tbl_gradecateg SET gg_hp = '".$sums."' where gg_id='".$id."'") or die(mysqli_error($con));
}
else
{
$queryhp = mysqli_query($con,"UPDATE tbl_gradecateg SET gg_hp = '".$sums."' where gg_id='".$id."'") or die(mysqli_error($con));
$sums= 0;
}
$id1= $num['gg_id'];
}
```
Any thoughts would be great.
A correlated subquery is a simple approach:
update tbl_gradesubcateg gs
set sg_grade = (select sum(sg.g_grade)
from gg_hp g
where g.gg_id = gs.gg_id
);
I don't recommend doing this calculation, though. It is simple enough to aggregate when you query the table. Summarizing the results just means that they are out-of-date the next time rows are inserted, updated, or deleted in the tables.

Mysql query to join two table and group by matching id

Am trying to group user orders by the order id, but am not getting it right i know this will be first get done in the SQL query then organise it well in PHP and HTML but i don't know how to get it done.
orderinfo
oid | userid | total | payid
-----|---------|--------|----------
oi10 | peter | 650 | VCC-100
oi12 | john | 30 | VCC-500
oi15 | peter | 60 | COD-500
itemorder
pid | ioid | userid | price | qty | itemname
----| ------|---------|--------|-----|-----------
p10 | oi10 | peter | 200 | 1 | lexus
p20 | oi10 | peter | 150 | 1 | Toyota
p15 | oi10 | peter | 300 | 1 | Myvi
p66 | oi15 | peter | 25 | 2 | BMW
p67 | oi15 | peter | 10 | 1 | Saga
p67 | oi12 | john | 10 | 3 | Saga
My current Code
$handler->prepare('
SELECT * FROM itemorder io
LEFT JOIN orderinfo oi
ON io.oid = oi.ioid
WHERE io.userid = 'peter'
GROUP BY io.oid
ORDER BY oi.pid DESC
');
$handler->execute();
$RecentOrder = $handler->getAll();
$handler->free();
if(!empty($RecentOrder)){
foreach($RecentOrder as $row){
}
}
Expected Result
I want the result to be sorted according to the order id all item that has same order id will be listed (list according to order id).
oid: oi10
--------
lexus
Toyota
Myvi
---------------------
oid: oi15
--------
BMW
Saga
The desired output can be retrieved with just ORDER BY.
SELECT *
...
ORDER BY oi.oid DESC, io.pid DESC
And then do the specific formatting in PHP. Easiest way is probably to remember the order_id of the last row.
$lastOrderId = null;
foreach ($result as $row) {
if ($lastOrderId != $row['oid']) {
echo 'oid: ' . $row['oid'] . PHP_EOL;
echo ' -----------' . PHP_EOL;
}
echo ' ' . $row['itemname'] . PHP_EOL;
$lastOrderId = $row['oid'];
}
You can try this :
SELECT io.ioid,GROUP_CONCAT("",io.itemname) as order_items FROM itemorder as io
LEFT JOIN orderinfo as oi
ON io.ioid = oi.oid
WHERE io.userid = 'peter'
GROUP BY io.ioid
ORDER BY io.pid DESC
Please not the columns on which join is done.
Then in PHP you can use explode function to get the array of names for each order.
Hope this helps!

Fetching/Putting 2 variables in a mysqli_num_row and mysqli_fetch_array in PHP

Basically I want to do a search by category and title. My problem is that the two are located in separate tables. I was thinking of putting 2 variables in the mysqli_num_rows or mysqli_fetch_array but I don't think it's the right idea. The $search variable is working already but I don't know what I will do for $searchcat that is a different table.
<table border="1">
<tr>
<th>ID</th>
<th>Survey Title</th>
<th>Category</th>
</tr>
<?php
if (isset($_POST['submit']))
{
include 'testdb.php'; //connection is written in other page (db.php)
$var =$_POST['search'] ;
$searchtype = $_POST['searchtype'];
$my_query="SELECT s.survey_id, s.title,c.categoryname
FROM survey_header as sh
JOIN survey AS s ON sh.survey_id=s.survey_id
JOIN category AS c ON sh.category_id=c.category_id
WHERE $searchtype LIKE '%".$var."%'
ORDER BY title ASC";
$get_data= mysqli_query($con, $my_query) or die ("Couldn't execute query: ".mysqli_error());
if (mysqli_num_rows($get_data) > 0 )
{
echo "<h3>Search results:</h3>";
while($show = mysqli_fetch_array($get_data))
{
$id = $show['survey_id'];
$title = $show['title'];
$category = $show['categoryname']; //
echo "<tr align='center'>";
echo "<td><font color='black'>" .$id. "</font></td>";
echo "<td><font color='black'>" .$title. "</font></td>";
echo "<td><font color='black'>" .$category. "</font></td>";
}
}
else{
echo "No Records found!";
}
}
?>
</table>
</body>
This is table category (categoryname is what I need)
+-------------+---------------+-------------+
| category_id | categoryname | datecreated |
| 1 | Philosophical | |
| 4 | Political | |
| 6 | Social | |
This is table survey (title is all I need)
| 1 | survey_id | title | description | duration | gender | age_group_from | age_group_to |
| 2 | 44 | game1 | description1 | 5 | male | 0 | 18 |
| 3 | 45 | game2 | description2 | 25 | female | 18 | 25 |
| 4 | 46 | game3 | description3 | 89 | female | 26 | 35 |
This is table survey_header (survey_id and category_id is what I need)
| 1 | survey_id | date_created | date_updated | opening_date | closing_date | category_id | topic_id |
| 2 | 33 | Not important | Not important | NULL | NULL | 1 | NULL |
| 3 | 45 | Not important | Not important | NULL | NULL | 6 | NULL |
| 4 | 46 | Not important | Not important | NULL | NULL | 4 | NULL |
Try this query :
$my_query="SELECT s.survey_id, s.title,c.categoryname
FROM survey_header as sh
JOIN survey AS s ON sh.survey_id=s.survey_id
JOIN category AS c ON sh.category_id=c.category_id
WHERE $searchtype LIKE '%".$var."%'
ORDER BY title ASC";
$get_data= mysqli_query($con, $my_query) or die ("Couldn't execute query: ".mysqli_error());
if (mysqli_num_rows($get_data) > 0 )
{
/*create table*/
}
else
// do something else

RSS Feed MySQL - Not displaying lowest MYSQL ID on GROUP

I am trying to create a RSS Script and have some Problem showing the lowest ID of nNr to show cPath (image)
MySQL Database seems like here
tartikel
+----------+-------+---------------------+------------+-------+
| kArtikel | cName | cKurzBeschreibung | dErstellt | cSeo |
+----------+-------+---------------------+------------+-------+
| 560 | 12345 | Short Description | 2014-03-25 | 12345 |
+----------+-------+---------------------+------------+-------+
| 561 | ABCDE | Short Description | 2014-03-25 | abcde |
+----------+-------+---------------------+------------+-------+
tartikelpict
+--------------+--------------+-------+
| kartikelpict | cPfad | nNr |
+--------------+--------------+-------+
| 560 | picture4.jpg | 4 |
| 560 | picture3.jpg | 3 |
| 560 | picture2.jpg | 2 |
| 560 | picture.jpg | 1 |
+--------------+--------------+-------+
| 561 | picture4.jpg | 4 |
| 561 | picture3.jpg | 3 |
| 561 | picture2.jpg | 2 |
| 561 | picture.jpg | 1 |
+--------------+--------------+-------+
My PHP Code
$result = mysql_query('SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM tartikel AS p1
JOIN tartikelpict AS p2
ON (p1.kArtikel = p2.kartikelpict)
JOIN (SELECT kartikelpict ,MIN(nNr) nNr FROM tartikelpict GROUP BY kartikelpict ) p3
ON(p2.kartikelpict = p3.kartikelpict AND p2.nNr = p3.nNr)
ORDER BY p1.kArtikel
DESC LIMIT 50', $connection);
while ($row = mysql_fetch_array($result)){
$cName = $row['cName'];
$cKurzBeschreibung = $row['cKurzBeschreibung'];
$dLetzteAktualisierung = $row['dLetzteAktualisierung'];
$dErstellt = $row['dErstellt'];
$cSeo = $row['cSeo'];
$date = strtotime($row['dErstellt']);
$pubdate = date(r, $date);
$id = $row['kArtikel'];
$nNr = $row['nNr'];
$cPfad = $row['cPfad'];
echo "\t\t" . '<enclosure url="'.$cPath.'" type="image/jpeg" />' . "\n";
The Result (it should be only the lowest)
<enclosure url="4" />
<enclosure url="3" />
<enclosure url="2" />
<enclosure url="1" />
I think I can't build the logic to get the right element. I have to get the ID of nNr and than select cPfad right? What am I doing wrong?
The SQL and Table seems to be OK after tested #sqlfiddle (thx to Khalid). Any idea what is wrong on my Code?

PHP select lowest ID of Group

How can I call the lowest ID (nNr) and the entry next to it ($cPfad) in PHP? I have 2 Tables and try to get from both of them the Details of an ID.
My SQL
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM tartikel AS p1
JOIN tartikelpict AS p2
ON (p1.kArtikel = p2.kartikelpict)
JOIN (SELECT kartikelpict, MIN(nNr) min_nNr FROM tartikelpict GROUP BY kartikelpict) p3
ON (p2.kartikelpict = p3.kartikelpict AND p2.nNr = p3.min_nNr)
ORDER BY p1.kArtikel
DESC LIMIT 10
DB Tables
+----------+-------+---------------------+------------+-------+
| kArtikel | cName | cKurzBeschreibung | dErstellt | cSeo |
+----------+-------+---------------------+------------+-------+
| 560 | Title | Short Description | 2014-03-25 | title |
+----------+-------+---------------------+------------+-------+
+--------------+--------------+-------+
| kartikelpict | cPfad | nNr |
+--------------+--------------+-------+
| 560 | picture4.jpg | 4 |
| 560 | picture3.jpg | 3 |
| 560 | picture2.jpg | 2 |
| 560 | picture.jpg | 1 |
+--------------+--------------+-------+
My PHP Code
while ($row = mysql_fetch_assoc($result)){
$cName = $row['cName'];
$cKurzBeschreibung = $row['cKurzBeschreibung'];
$dLetzteAktualisierung = $row['dLetzteAktualisierung'];
$dErstellt = $row['dErstellt'];
$cSeo = $row['cSeo'];
$date = strtotime($row['dErstellt']);
$pubdate = date(r, $date);
$id = $row['kArtikel'];
$nNr = $row['p3.min_nNr'];
$cPfad = $row['cPfad'];
echo"<item>";
echo"<title><?php echo $cName; ?></title>";
echo"<link>http://domain.com/".$cSeo."</link>";
echo"<guid isPermaLink='false'>http://domain.com/".$cSeo."></guid>";
echo"<pubDate>".$date."</pubDate>";
echo"<description><![CDATA[ <img src='http://domain.com/bilder/produkte/normal/".$row['nNr']."' />".$cKurzBeschreibung." ]]></description>";
echo"<enclosure url='http://domain.com/bilder/produkte/normal/'".$nNr." type='image/jpeg' />";
echo" </item>";
}
The call of $cPfad does not output anything, the call of of $nNr call each ID instead of the lowest one to get the correct $cPfad. What am I doing wrong im my PHP Code?

Categories