This question already has answers here:
Return row only if value doesn't exist
(2 answers)
Search with comma-separated value mysql
(1 answer)
Closed 1 year ago.
Currently have hit a mental wall in my project. Brief summary. We have a table for completed courses on our site. Courses can be put in a plan. Trying to build a CSV export report that will show incompletions/completions so a manager can see progress for their environment and thus get with the employee to finish the plan.
Reports Table:
ID|UID|CID|Completed Date|
1 | 1 |78 |09-14-2021
2 | 1 |79 |09-14-2021
3 | 1 |75 |09-14-2021
4 | 1 |76 |09-14-2021
5 | 1 |77 |09-14-2021
Course table:
ID|NAME | credits | some other info
78|test
79|test2
75|test3
76|test4
77|test5
80|test6
Plan Table:
ID| Courses
8 | 75,76,77,78,79,80
I have the report generating all completions accurately my issue is when it doesn't exist in the completed table since the user hasn't finished it.
I use an if(isset reports.id) to dump info and an else statement to change the date to "incomplete"
My issue is populating the name for that course on the report. I'm not sure of how to check against data that doesn't exist. So in this example the course array would be [78,79,75,76,77,80] but the reports table only has completions for 75,76,77,78,79. The else statement is dumping $x[0] which the first result is "test". So I know my logic is wrong. But for the life of me can't think of the correct way to get the right information.
I need the else state ment to dump the remaining courses that aren't represented in the reports table as they are not complete. Any ideas?
Report Looks like this
Query for $courses array
"SELECT id, name, credits FROM `courses` WHERE id IN (78,79,75,76,77,80) ORDER BY id")
$courses[] = array($course_data['course_name'], $course_data['credits'],$course_data['id']);
//$exportdata is my SQL pull for all info.
if (isset($exportdata['reports.id'])) {
$completeddate = $exportdata['completed_date'];
$credit = $exportdata['credits'];
$coursename = $exportdata['course_name'];
} else {
foreach ($courses as $x) {
$credit = "-";
$completeddate = 'Incomplete';
$coursename = $x[0];
}
}
Excel function dumps $name, $email, $coursename, $completeddate, $credits in a row.
Related
I have a db table with in one column the province name of a country. And in another column of the same table the amount of people living in this province.
There are many more columns in the table and also postal codes. As the postal codes are unique you can see in this table that the province column has a lot of equals.
Sample data:
id | postal code | province | amount
1 | 1001 | Amsterdam | 500
2 | 1002 | Amsterdam | 1500
3 | 1003 | Amsterdam | 250
In a form that I am creating I need to create checkboxes for each province and the value of the checkbox needs to be the amount value.
For this I use the below code. (This code is inserted into a Form Builder called RS Form so it might look a bit strange but please believe me it is working.
The form builder creates the checkboxes it only needs the 'grab from db' part not the echo checkboxes part).
<?php
//<code>
$db =& JFactory::getDBO();
$db->setQuery("SELECT province, amount FROM `#_the_correct_table`");
$results = $db->loadObjectList();
foreach ($results as $result) {
$value = $result->amount;
$label = $result->province;
$items[] = $value.'|'.$label;
}
// Multiple values are separated by new lines, so we need to do this now
$items = implode("\n", $items);
// Now we need to return the value to the field
return $items;
//</code>
?>
The above code is currently generating about 4000+ checkboxes with lots of duplicates, so I have been looking into outputting each province only once and making it calculate the amounts. So with the above example I would get 1 checkbox Amsterdam = 2250.
I am struggling with getting this code which should do this combining to work with the code I already have.
$sum = 0;
foreach($quantity as $value) $sum = $sum + $value;
echo $sum;
Can someone please show me how to combine it?
No need to do it using PHP. This is a standard SQL task.
You need to perform 2 operations:
group your records by province name (Amsterdam for example)
sum amount values for grouped rows
Just change your SQL query to something like:
SELECT SUM(amount) as province_sum
FROM tbl
GROUP BY province
Here is the SQL fiddle: http://sqlfiddle.com/#!9/9cbf9d/1
QUERY:
SELECT month(date_created), count(a.ticket_num)
FROM ticket as a
LEFT JOIN user_management as b on b.engineer_id = a.ticket_engineer
WHERE b.tl_id = 'sample_id'
AND year(date_created) = '2019'
GROUP BY extract(year from date_created), extract(month from date_created)
SAMPLE OUTPUT:
month | ticket_num
----------------------
2 | 12
4 | 24
6 | 78
EXPECTED SAMPLE OUTPUT:
month | ticket_num
----------------------
1 | 0
2 | 12
3 | 0
4 | 24
5 | 0
6 | 78
As you can see the above expected output, i'm trying to place all existing month in the first column and set all the count to zero if not existed in the second column. As of now, i only have the query for sorting the ticket count by month that is existed when the ticket is created.
There are different approaches to this problem. One is pure SQL for example.
But I would say a PHP based solution is simpler. Basically you need to get your data into array, then create a loop that outputs the desired months order, and have a condition that sees whether we have a corresponding row in our array and outputs ether the actual data or a zero accordingly.
The only tricky part is to have such an array that would let us check the data availability. For this we have to index it with month numbers. Not a big deal actually
$sql = "SELECT month(date_created), count(a.ticket_num) ...";
$res = $mysqli($sql);
$data = [];
while($row = mysqli_fetch_row($res)) {
$data[$row[0]] = $row[1];
}
Now $data is an array indexed by the month number. The rest is a primitive loop
foreach (range(1,12) as $month) {
echo $data[$month] ?: 0;
}
On a side note I would like to advertise using PDO as opposed to mysqli for your database interactions as this case clearly displays the superiority of the former. Using PDO we can get the indexed array right away, without an explicit loop, thanks to a special fetch mode:
$sql = "SELECT month(date_created), count(a.ticket_num) ...";
$data = $data = $pdo->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);
That's all!
I have a table in MySQL, with 5(sort of) possible values in the column 'type'... I say sort of because the data type is 'set' and 1 type has a subcategory... It's for a type of property, so the possible types are retail, office, hospitality, industrial, residential(multi family), residential(single family).
I'm attempting to paginate the results and I need to know how many pages each should have. So I need a query that tells me how many of each type are in the table, the user can select residential as a category, or single, multi as subcategories.
I can't figure out how to do a query that tells me how many of each there are, or how to retrieve those numbers as variables I can use to divide be items per page.
id | type
-----------------------
1 | office
2 | residential,single
3 | industrial
4 | residential,multi
5 | retail
6 | office
7 | hospitality
8 | residential,single
etc....
so if this was the data, I would need to get:
$office = 2
$residential = 3
$industrial = 1
$single = 2
etc...
Use array_count_values() function
Check the link http://php.net/manual/en/function.array-count-values.php
From their website http://php.net/manual/en/function.array-count-values.php;
and Try this code
<?php
$query= // Run your select query.
$result= mysqli_query($link, $query);
//Run the while loop
while($row= mysqli_fetch_array($result))
{
$array[]=$row['Column_Name'];//Store the result in array
}
$count = array_count_values($array);//Use array count
print_r($count);//See the result
Or if you see The out put the way you want
Run Foreach loop on the $count array
foreach($count as $key => $value) {
//Get the out put From new array
echo $value .' '. $key.'<br/>' ;
}
A count and group by should do the trick;
SELECT id, type, COUNT(*) as count
FROM mytable
GROUP By id
I am currently using the following query to retrieve data from a database:
SELECT product_Id, COUNT(product_Id) as count
FROM my_sales
GROUP BY product_Id
ORDER BY count DESC
in phpmyadmin it looks like this:
_____________________________________
Product_ID | count
__________________|__________________
12 | 13
13 | 21
14 | 24
The PHP Code im using looks like this:
$res = $connVar->prepare($query); //the query described above
$res->execute();
$res->fetch(PDO::FETCH_ASSOC);
while ( $row = $res->fetch(PDO::FETCH_ASSOC) )
{
$data[] = $row;//return the information from the database as an array
echo $data[0]['product_Id']; //trying to target specific indexes of an associative array :/
echo $data[0]['count'];
}
What really needs to happen is that I can store each row as variables so that I can say, print out in php how much stock is left for a particular product.
Been looking on stackoverflow for around 4 hours now and about to give up. There are a lot of questions available about returning the whole dataset within one variable but thats not what i need.
Any help?
This question already has an answer here:
mysql don't count row twice if column data is duplicated
(1 answer)
Closed 9 years ago.
i have a a table called ptb_profile_views;
id | profile_id | viewed_profile | date
1 1 5
2 1 5
3 1 5
4 2 5
5 3 5
ok so in this example users 1,2 ans 3 are checking out user 5's profile,
the mysql i've got here is suppose to count the number of views a user has got, but where user 1 has checked out user 5 several times i do not want to return duplicate rows,
so instead of saying user 5 has been viewed 5 times, they will have only actually been viewed 3 times because i only want to count distinct values.
heres my mysql can someone please help me:
function check_profile_views() {
global $connection;
global $_SESSION;
$query = "SELECT COUNT(profile_id) FROM ptb_profile_views WHERE viewed_profile_id=".$_SESSION['user_id']." AND profile_id!='0'";
$check_profile_views_set = mysql_query($query, $connection);
confirm_query($check_profile_views_set);
return $check_profile_views_set;
}
the php:
$check_profile_views_set = check_profile_views();
while ($views = mysql_fetch_array($check_profile_views_set)) {
?>
<? echo"". $views['COUNT(profile_id)'] ."";?> viewed your profile
just add DISTINCT
SELECT COUNT(DISTINCT profile_id) totalCOUNT FROM ptb_profile_views...
and echo the alias,
$views['totalCOUNT']
SQLFiddle Demo