-2

I've been searching for the better part of five days (no joke, don't want to bother you guys for nothing), but I can't seem to be getting this right. I want to display the total amount of a column (tech) on the screen using a function in PHP. Don't worry, the $day part works in other functions. I don't think it is part of the problem. Thank you in advance.

function calc_tech($day){

    include("connect.php"); // include database connection

    $res = $mysqli -> query(" SELECT * FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table

    while($val = $res -> fetch_array()){
        $tech_total = $val[tech] += $val[tech];
    }

    echo $tech_total; // Echo the result
    //echo "42";

    $res -> free(); // Free the query results
    $mysqli -> close(); // Close mysqli object

}

My database table looks like this:

enter image description here

4
  • select sum(tech) from sales where day='$day'; Commented May 9, 2017 at 4:02
  • What output do you want here? Commented May 9, 2017 at 4:03
  • So, what isn't working? Commented May 9, 2017 at 4:04
  • 2
    42+0+0+42 = 42 how is it 42 ? @adesgangne ?? Commented May 9, 2017 at 4:09

1 Answer 1

1

You need to make the SUM() the column in the query :

function calc_tech($mysqli,$day){
    //Prepare your query first
    $stmt = $mysqli->prepare("SELECT SUM(tech) FROM sales WHERE day=?"); 
    // then bind the parameter
    $stmt->bind_param("s", $day);
    // then execute the query
    $stmt->execute();
    $result = $stmt->get_result();
    // fetch and return the result
    return $result->fetch_row()[0];
}

include("connect.php"); // include database connection
echo calc_tech($mysqli,$day); // get the result
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.