if I have this SQL query:
select substring(id for 2) as key,
yw, count(*)
from pref_money group by yw, key
returning number of users per week and per key:
key | yw | count
-----+---------+-------
VK | 2010-45 | 144
VK | 2010-44 | 79
MR | 2010-46 | 72
OK | 2010-48 | 415
FB | 2010-45 | 11
FB | 2010-44 | 8
MR | 2010-47 | 55
VK | 2010-47 | 136
DE | 2010-48 | 35
VK | 2010-46 | 124
MR | 2010-44 | 40
MR | 2010-45 | 58
FB | 2010-47 | 13
FB | 2010-46 | 13
OK | 2010-47 | 1834
MR | 2010-48 | 13
OK | 2010-46 | 1787
DE | 2010-44 | 83
DE | 2010-45 | 128
FB | 2010-48 | 4
OK | 2010-44 | 1099
OK | 2010-45 | 1684
DE | 2010-46 | 118
VK | 2010-48 | 29
DE | 2010-47 | 148
Then how can I please count those users? I'm trying:
$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
from pref_money group by yw, key');
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
++$users[$row['yw']][$row['key']];
print_r($users);
but get numerous errors.
I'm trying to get the data for a stacked bars diagram. The x-axis will show the week numbers and the y-axis will show number of users, grouped by the key strings.
Thank you! Alex
Are you trying to total the count column or just get number of rows returned? If the latter, php has a method for that. if the former, you need to make it $users[$row['yw']][$row['key'] += $row['count'] instead (assuming the array has already been created).
$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
from pref_money group by yw, key');
$sth->execute();
$users=array(); // register $users as an array.
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
if(!isset($users[$row['yw']])){// see if $users['whatever_key'] has already been set
$users[$row['yw']]=0;//if not, initialize it as a default starting value of 0
}
$users[$row['yw']]+=$row['key'];//now we won't get any nasty notices here about undeclared variables or keys..
print_r($users);
Related
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.
I've two tables:
___Rooms:
|--------|------------|
| ROO_Id | ROO_Status |
|--------|------------|
| 47 | active |
| 48 | active |
| 49 | active |
|--------|------------|
___Availabilities:
|--------|------------|------------|------------|
| AVA_Id | AVA_RoomId | AVA_Date | AVA_Status |
|--------|------------|------------|------------|
| 1 | 47 | 2019-02-25 | Open |
| 2 | 48 | 2019-02-26 | Open |
| 4 | 47 | 2019-02-28 | Close |
| 5 | 47 | 2019-02-25 | Open |
|--------|------------|------------|------------|
I would like to get info for both of these tables for a range of dates.
So my query is the following:
SELECT ROO_Id, AVA_Id, AVA_Date, AVA_Status
FROM ___Rooms
LEFT JOIN ___Availabilities
ON ___Rooms.ROO_Id = ___Availabilities.AVA_RoomId
WHERE ROO_Status!="inactive"
AND AVA_Date BETWEEN "2019-02-24" AND "2019-03-10"
ORDER BY ROO_Id ASC
The problem is the query don't take all the ___Rooms rows. For example, Room #49 don't have a record in ___Availabilities but I need to have it in the final result.
Do you know why ?
Thanks.
Using a left join is correct, but by filtering on the AVA_Date column in a where clause you will exclude any rows where AVA_Date is null.
Move that filter to the on clause and your left-join will work as expected
SELECT ROO_Id, AVA_Id, AVA_Date, AVA_Status
FROM ___Rooms
LEFT JOIN ___Availabilities
ON ___Rooms.ROO_Id = ___Availabilities.AVA_RoomId
AND AVA_Date BETWEEN "2019-02-24" AND "2019-03-10"
WHERE ROO_Status!="inactive"
ORDER BY ROO_Id ASC
How to resolve this?
Notice: Undefined index: Ans in C:\wamp64\www\quiz\remove\repeated.php on line 13
My code:
require_once '../class.user.php';
$user_home = new USER();
$lstmtf = $user_home->runQuery("SELECT COUNT(Ans)
FROM answer AS a
LEFT JOIN students_records AS s ON a.Sr = s.Sr
WHERE s.Sr IS NULL");
$lstmtf->execute();
$reg_rst = $lstmtf->fetch(PDO::FETCH_ASSOC);
$registered= $reg_rst['Ans'];
echo $registered;
My table answer has column name Ans.
Actually, I want to count the numbers of rows which do not have values in students_records.
For Eg:
students_records
+----+-----+-----+
| Sr | SRN | ARN |
+----+-----+-----+
| 1 | ge | aj |
| 2 | ge | bd |
+----+-----+-----+
answer
+----+-----+-----+
| Sr | SRN | ARN |
+----+-----+-----+
| 1 | ge | aj |
| 2 | ge | aj |
| 3 | ge | ne |
| 4 | ge | bd |
+----+-----+-----+
Here count should be 1. As the value "ne" in column ARN of table answer is no where in the rows of column ARN in table students_records.
Use like this
$lstmtf = $user_home->runQuery("SELECT COUNT(Ans) as Ans
FROM answer AS a
LEFT JOIN students_records AS s ON a.Sr = s.Sr
WHERE s.Sr IS NULL");
You can get the desire output by following
SELECT count(a.Ans) as ans
FROM answer AS a
LEFT JOIN students_records AS s ON a.ARN = s.ARN
WHERE s.ARN IS NULL
Here is working example
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?
How can I use $row results into a mysqli_query?
$result1 = mysqli_query($connect,"SELECT subcat_ID FROM subcategories WHERE cat_ID=$cat_ID");
$row=mysqli_fetch_array($result1);
$result2 = mysqli_query($connect,"SELECT subsubcat_name FROM subsubcategories WHERE subcat_ID='".$row['subcat_ID']."'");
while ($row = mysqli_fetch_array($result2)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
I don't get any error but I can't get it printed.
Any idea what I'm doing wrong?
Thanks for any help!
==================================================================================
1st edit
Because my problem isn't solved yet, I'm explaining it a bit more in depth:
My databases:
- categories: cat_ID, cat_name
- subcategories: subcat_ID, cat_ID, extra_cat_ID, subcat_name
- subsubcategories: subsubcat_ID, subcat_ID, subsubcat_name
At a certain point I get the value of a cat_ID (categories) through an url.
What I want to do is wherever cat_id of categories is the same value as the cat_id or extra_cat_ID like in subcategories (I also want to be able to print subcat_name), where subcat_ID of subcategories is the same as subcat_ID of subsubcategories ---> print subsubcat_name.
Categories
-------------------------
cat_ID | cat_name
------------------
4 | Baby & Kids
5 | Bicycles
6 | Boats
7 | Books & Comics
....
13 | Clothes & Accessories
....
35 | Sport & Fitness
36 | Study
....
38 | Toys & Games
....
Subcategories
-------------------------
subcat_ID | cat_ID | extra_cat_ID | subcat_name
------------------------------------------------
....
15 | 4 | 13 | Baby clothes
16 | 4 | 0 | Baby products
17 | 4 | 13 | Kids clothes
18 | 4 | 38 | Toys
19 | 5 | 0 | Bycicles
20 | 5 | 0 | Bycicle gear & Accessories
21 | 6 | 0 | Boat parts
22 | 6 | 0 | Other Boats
23 | 6 | 0 | Power Boats
24 | 6 | 0 | Sailboats
25 | 6 | 35 | Windsurf & Surfing
26 | 7 | 0 | Antiquarian
27 | 7 | 0 | Books
28 | 7 | 38 | Childrens books
29 | 7 | 0 | Comics
30 | 7 | 0 | Magazines & Newspapers
31 | 7 | 36 | Study & Training
Subsubcategories
-------------------------
subsubcat_ID | subcat_ID | subsubcat_name
-----------------------------------------
...
470 | 15 | Baptism outfits
471 | 15 | Bibs
472 | 15 | Body warmers
473 | 15 | Bodysuits
....
496 | 16 | Baby bath
497 | 16 | Baby books
498 | 16 | Baby inserts
499 | 16 | Baby monitors
....
548 | 17 | Belts
549 | 17 | Blouses & Shirts
550 | 17 | Body warmer
551 | 17 | Boots
....
....
740 | 26 | Music
741 | 26 | Navy
742 | 26 | Novel
743 | 26 | Photography
....
....
867 | 30 | Animals
868 | 30 | Arts and Culture
869 | 30 | Branch
870 | 30 | Cars
870 | 30 | Computers
....
....
etc.
I hope this clearout things a bit more.
Instead of running two queries you should use a JOIN.
For example this $query :
SELECT subcategories.cat_ID, subsubcategories.subsubcat_name
FROM subcategories
INNER JOIN subsubcategories
ON subcategories.cat_ID=subsubcategories.subcat_ID
WHERE subcategories.cat_ID = ?
Preparing your query is more appropriate/safe in this case:
/* create a prepared statement */
if ($result = mysqli_prepare($connect, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($result, "i", $cat_ID);
/* execute query */
mysqli_stmt_execute($result);
/* fetch data */
while ($row = mysqli_fetch_array($result)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
}
}
DEMO for SQL JOIN
Got it working. This is the code I used:
$result=mysqli_query($connect,"SELECT subcategories.cat_ID, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = $cat_ID OR subcategories.extra_cat_ID = $cat_ID");
while ($row = mysqli_fetch_array($result)){
echo $row['subsubcat_name'];
echo "<br>";
}
Though not sure it is the safe way to do it. Suggestions are always welcome.
Thanks to meda to showing me another approach tho it is not quite the same code.
Here is an example on how to use mysqli
object oriented
<?php
$connect= new mysqli("localhost","user","passwd","database");
if ($connect->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $connect->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$connect->close();
?>
Procedural Style
<?php
$connect= mysqli_connect("localhost","user","passwd","database");
if (mysqli_connect_errno()){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = mysqli_query($connect,$select)){
while($row = mysqli_fetch_object($result)){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
mysqli_close($connect);
?>