PHP Getting SUM of Array Values While Comparing - php

I have an array of Information States And Totals. I want to see how to get the Total of all the Totals for each state.
I know I have to use a loop but I am not sure which - what would I do?
This is what I have so far. It's making the array from a database.
$WorkFind = mysql_query(
"SELECT Customers.State, WorkOrders.Total
FROM WorkOrders
INNER JOIN Customers
ON WorkOrders.CID=Customers.ID
WHERE WorkOrders.Type <> 'Warranty'
AND (WorkOrders.Status <> 'Closed'
OR WorkOrders.Status <> 'Cancelled')
AND WorkOrders.TransferID='0'
ORDER BY Customers.State ASC");
while ($Work = mysql_fetch_array($WorkFind)) {
}
The while loop has made the array but I'm unsure what to put into it.
I'm using PHP 5.3 and MYSQL 5.2

Try this:
$WorkFind = mysql_query("SELECT Customers.State AS State, WorkOrders.Total AS Total -- ...");
$total = array();
while ($Work = mysql_fetch_array($WorkFind)) {
$state = $Work['State'];
if (!isset($total[$state])) {
$total[$state] = 0;
}
$total[$state] += $Work['Total'];
}
// format as simple table
echo '<table><tr><th>State</th><th>Total</th></tr>';
foreach ($total as $state_name => $state_total) {
echo '<tr><td>' . $state_name . '</td><td>' . $state_total . '</td></tr>';
}
echo '</table>';

Related

PHP MYSQL Results into a table

I have a PHP/MySQL query that returns the following:
array ( 'name' => 'Jess', 'month' => '2020-03-31 12:28:00', 'count' => '1', )
array ( 'name' => 'Bob', 'month' => '2020-04-31 12:28:00', 'count' => '2', )
array ( 'name' => 'Tom', 'month' => '2020-05-31 12:28:00', 'count' => '2', )
array ( 'name' => 'Bob', 'month' => '2020-05-31 12:28:00', 'count' => '2', )
The months return in an ordered fashion (E.g. January records are always before February records).
However, not every user will have a result every month (see above).
And I want my data to present such as this, in an html table:
Month Jess Bob Tom
March 1
April 2
May 2 2
Here is my (non working) attempt:
<?php
/*loop through all customers and print out each induvidual users performance*/
$con = mysqli_connect("localhost","root","","perfmon");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
//main query for customer names
if ($customers = mysqli_query($con, "SELECT Distinct(customer_name) FROM slog ORDER BY customer_name DESC;")) {
while($row=mysqli_fetch_assoc($customers))
{
$name = $row["customer_name"];
print("<b>".$name." </b><br>");
$total = 0;
$cur_month = NULL;
$namepos = array();
$th = "<th>Month</th>";
$tr = "";
$npcount = 0;
//Loop over the customer names, and pull the modified count per user.
if ($user_perf = mysqli_query($con, "select modified_by as name, created_date as month, count(modified_by) as count from slog where customer_name = '$name' group by modified_by, MONTH(created_date) order by month;")) {
while($row=mysqli_fetch_assoc($user_perf))
{
//Assign variables from mysql results
$month = date("F",strtotime($row["month"]));
$name = $row["name"];
$count = $row["count"];
$total += $row["count"];
//Only add the month once!
if($cur_month != $month){
$cur_month = $month;
$tr .= "</tr><tr><td>" . $cur_month. "</td>";
//print($cur_month . "<br>");
}
//store the username 'position' to build a table (this determines how many spaces are needed.)
if(!array_key_exists($name,$namepos))
{
$namepos[$name] = $npcount;
$npcount += 1;
$th .= "<th>" .$name . "</th>";
}
//add details to tr in correct pos
for( $i = 0; $i < $namepos[$name]; $i++){
$tr .= "<td></td>";
}
$tr .= "<td> ".$count." </td>";
//print(" ".$name . " " . $count . " <br>");
}
print("<table border='1'><tr>". $th . "</tr>" . $tr . "</table>");
print("<br>Total: ".$total." <br><br> ");
mysqli_free_result($user_perf);
}
}
mysqli_free_result($customers);
}
mysqli_close($con);
?>
Which unfortunately results in results such as this:-
What would be the best way to achieve this?
I have tried storing the position of each user in the table headers, but then it is difficult to know how many empty columns to add before and the entry (see image above).
just a quick update. I have managed to get what I desired through the following code
<?php
/*loop through all customers and print out each induvidual users performance*/
$con = mysqli_connect("localhost","root","","perfmon");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
//main query for customer names
if ($customers = mysqli_query($con, "SELECT Distinct(customer_name) FROM slog ORDER BY customer_name DESC;")) {
while($row=mysqli_fetch_assoc($customers))
{
//Name of customer
$name = $row["customer_name"];
//Print customer name
print("<b>".$name." </b><br>");
//Used to display total jobs
$total = 0;
$user_list = array("Month");
$monthlist = array();
$st_array = array();
//Loop over the customer names, and pull the modified count per user.
if ($user_perf = mysqli_query($con, "select modified_by as name, created_date as month, count(modified_by) as count from slog where customer_name = '$name' group by modified_by, MONTH(created_date) order by month;")) {
while($row=mysqli_fetch_assoc($user_perf))
{
$month = date("F",strtotime($row["month"]));
$name = $row["name"];
$count = $row["count"];
$total += $row["count"];
//make our left column (months)
if(!in_array($month, $monthlist)){
array_push($monthlist, $month);
}
//Collect all unqiue users, to make our headers array. also stores the order theyre in.
if(!in_array($name, $user_list)){
array_push($user_list, $name);
}
//make a 2d array of all data
$tmp = [$month, $name, $count];
array_push($st_array, $tmp);
}
/**Process fetched data **/
$row = "";
$previous_pos = 1;
$fe = True;
//Print each unique user as a table header
print("<table border='1'>");
print("<tr>");
foreach ($user_list as $th){
print("<th>".$th."</th>");
}
print("</tr>");
//Loop the month array
foreach ($monthlist as $td){
//Loop the user array
foreach ($user_list as $usr){
//Loop our "2d" array (an array containing Month,User,Count)
foreach($st_array as $array_2d){
//If we match the correct month and user, return the count value. This ensures the users return in the correct order.
if ($array_2d[0] == $td && $array_2d[1] == $usr){
//Pos - Get the current position of the selected user.
//Establish how many empty entries need to come before. E.g. User in col 1 has no empty entries infront. User in column2 has 1 entry empty infront (if column 1 is empty).
$pos = array_search($usr, $user_list);
if ($previous_pos != $pos){
$row .= str_repeat("<td>0</td>", ($pos-$previous_pos-1));
}
//Assign our previous position
$previous_pos = $pos;
//If our first entry isn't in column 1, add an extra 0.
if($pos!==1 && $fe)
$row .= "<td>0</td>";
$fe = False;
//Add the data
$row .= "<td>".($array_2d[2])."</td>"; //change to [1] for debug
}
}
}
//Print the table row.
print("<tr><td>".$td ."</td>" . $row ."</tr>");
//Reset our variables.
$row = "";
$fe=True;
$previous_pos = 1;
$first_result = True;
}
print("</table></br>");
mysqli_free_result($user_perf);
}
}
mysqli_free_result($customers);
}
mysqli_close($con);
?>
Essentially I created 3 arrays. An array of users, an array of months, and an array of all data (3d array). I use the months and users to record the order in which the tables should be presented. I then loop through my 3d array and print the relevant data.
Despite the downvotes, I would like to thank you all for offering your help. If you have any recommendations please let me know.

fetch and check cart data with php mysql

I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}

running a query inside a loop to do another loop

Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id

Displaying values from mysqli with loop

I need to be able to display the course_desc on line 30, beside the course_name.
<?php
$result = $db->query("select distinct c.dbid, c.course_name, c.course_image, m.module_id, m.module_name, m.module_name_id, m.module_image, m.hasFiles, m.files from courses c join modules_to_courses mc on (c.dbid = mc.courses_id) join modules m on (mc.modules_id = m.module_id)");
$course_name = $db->query("SELECT distinct course_name, course_desc FROM courses");
while ($temp = $course_name->fetch_assoc()) {
$courses[] = $temp['course_name'];
}
$final = array();
// Retrieve results
while ($row = $result->fetch_assoc()) {
// Add to final array via counter if valid course is found
if (in_array($row['course_name'], $courses)) {
$final[$row['course_name']][] = $row;
}
}
// Display if final array is not empty
if (!empty($final)) {
// Loop through each potential course name
foreach ($courses as $name) {
// Output if the course has values within the final array
if (array_key_exists($name, $final)) {
echo '<div>'."\n";
echo ' '. $name . "\n";
echo '<!-- list of modules -->'."\n";
// Loop through internal values
foreach ($final[$name] as $value) {
$module_name = $value['module_name'];
echo ' '. $module_name ."\n";
}
echo ' </div>'."\n";
}
}
}
?>
You already having your course description in $final so you can access it using,
$final[$name]['course_desc']
I have created a paste based on your with changes. Also note that it's need to change your $final array.
distinct course_name, course_desc means you are trying to fetch the values regarding to distinct course_name and distinct course_desc together. You may wanna use group by instead. If I understood correctly, your statement will not bring you distinct course names and their related course desc. (if that is what you want)

PHP/MySQL How do I remove duplicate information from a LEFT JOIN?

I am trying to generate a simple list from a series of tables in a MySQL database. The SQL I am using is:
$resource_sql = "SELECT prod_spec_sheets.spec_uri, prod_spec_sheets.spec_title,
prod_photos.photo_uri, prod_photos.photo_title,
prod_diagrams.diag_uri, prod_diagrams.diag_title,
prod_ies.ies_uri, prod_ies.ies_title,
prod_instruction_sheets.instr_sheet_uri, prod_instruction_sheets.instr_sheet_title
FROM products
LEFT JOIN prod_spec_sheets ON products.prod_id = prod_spec_sheets.prod_id
LEFT JOIN prod_photos ON products.prod_id = prod_photos.prod_id
LEFT JOIN prod_diagrams ON products.prod_id = prod_diagrams.prod_id
LEFT JOIN prod_ies ON products.prod_id = prod_ies.prod_id
LEFT JOIN prod_instruction_sheets ON products.prod_id = prod_instruction_sheets.prod_id
WHERE products.prod_code = '$product_code'";
The PHP I am using to display it looks like this:
if ($resource_num_rows > 1){
echo '<h2>Downloads</h2>';
while($row = mysql_fetch_array($resource_result, MYSQL_ASSOC)){
echo "<ul>";
$count = 0;
foreach ($row as $key => $value) {
if ($count % 2) {
echo '">' . $value . '</a></li>' . PHP_EOL;
} else {
echo '<li><a href="' . RESOURCES_URI . $value;
}
$count++;
}
echo "</ul>";
}
}
Which generates the following HTML:
<ul>
<li>Specs</li>
<li>Photo</li>
<li>Diagram</li>
<li>Instructions</li>
</ul><ul><li>Specs</li>
<li>Photo</li>
<li>Diagram</li>
<li>Instructions (ALT)</li>
</ul>
When what I really need is:
<ul>
<li>Specs</li>
<li>Photo</li>
<li>Diagram</li>
<li>Instructions</li>
<li>Instructions (ALT)</li>
</ul>
Each table (except products) could have many items associated with a product, this example only shows what happens if there is more than one set of instructions in the prod_instruction_sheets table.
I'm not sure if the answer is in a better MySQL statement, or a change in the PHP to my loop. Any help would be gratefully received.
Try to SELECT only the field you need and use the keyword DISTINCT in your statement:
$resource_sql = "SELECT DISTINCT prod_spec_sheets.spec_uri, prod_spec_sheets.spec_title,
prod_photos.photo_uri, prod_photos.photo_title,
prod_diagrams.diag_uri, prod_diagrams.diag_title,
prod_ies.ies_uri, prod_ies.ies_title,
prod_instruction_sheets.instr_sheet_uri, prod_instruction_sheets.instr_sheet_title
FROM products
LEFT JOIN prod_spec_sheets ON products.prod_id = prod_spec_sheets.prod_id
LEFT JOIN prod_photos ON products.prod_id = prod_photos.prod_id
LEFT JOIN prod_diagrams ON products.prod_id = prod_diagrams.prod_id
LEFT JOIN prod_ies ON products.prod_id = prod_ies.prod_id
LEFT JOIN prod_instruction_sheets ON products.prod_id = prod_instruction_sheets.prod_id
WHERE products.prod_code = '$product_code'";
Edit:
Ok i see what you are doing, one easy way to filter this column in PHP is to put the line you are writting into an associative array and check if you have already write back this data.
Move also your UL outside of the while loop if you don't have two list.
Example:
if ($resource_num_rows > 1){
echo '<h2>Downloads</h2>' . PHP_EOL . '<ul>' . PHP_EOL;
$seen=array(); //use to filter te line written
while($row = mysql_fetch_array($resource_result, MYSQL_ASSOC)) {
$count = 0;
foreach ($row as $key => $value) {
if ($count % 2) {
$line .= '">' . $value . '</a></li>';
// check if the line has already been output
if (!array_key_exists($line, $seen)) {
// no mark it as written
$seen[$line]=true;
// and output the line
echo $line . PHP_EOL;
}
} else {
$line='<li><a href="' . RESOURCES_URI . $value;
}
$count++;
}
}
echo "</ul>";
}
GROUP BY products.prod_id smells like it should work at first glance.

Categories