Pass mySQL Data into a php function

I want to pass some data when I run a query to add some data in mySQL 4 numeric fields which will be added to create a total. I have tried several ways to do this put nothing is working here is my code:

$custID = $_POST["custID"];
$cID1 = $_POST["cID1"];
$cTravelExp = $_POST["cTravelExp"];
$cLodgeExp = $_POST["cLodgeExp"];
$cFoodExp = $_POST["cFoodExp"];
$cOtherExp = $_POST["cOtherExp"];
$sqlSearch = "SELECT * FROM $tableName WHERE custID ='$custID' AND cID1= '$cID1' ";
$result = $conn->query($sqlSearch);

function addTotal($cLodgeExp,$cTravelExp,$cFoodExp,$cOtherExp){
	$vacTotal = $cLodgeExp+$cTravelExp+$cFoodExp+$cOtherExp;
	return $vacTotal;
	
}

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Search results are "."Customer id: " . $row["custID"]." "."Yellowstone Plan Number: "." ".$row["cID1"]." "."First Name: ".$row["cFName"]." "." Last Name: " ." ".$row["cLName"]. " Plan Name: " 
		." ". $row["cPlanName"]." "." Travel Method ".$row["cTravel"]." Travel Expenses ".$row["cTravelExp"]. " Lodging Expenses ".$row["cLodgeExp"]." Food Expenses ".$row["cFoodExp"].
		" Other Expenses ".$row["cOtherExp"]."<br>"."Total package price is ".addTotal($cTravelExp,$cLodgeExp,$cFoodExp,$cOtherExp);
    }

My connection works but my total produces a zero every time?

Just alter your query to include the total. You can just do something like:
SELECT *, (cLodgeExp + cTravelExp + cFoodExp + cOtherExp) AS total FROM $tablename WHERE etc…
Then, when you do the query, you can just display the total as:
echo $row[ “total” ];

Should make it easier that processing it in PHP. Let the SQL engine do the work.

You are calling the function with values that have no value. It looks like you want to pass in the values retreived from the data record, so use them,

addTotal($row['cLodgeExp'[,$row['cTravelExp'],$row['cFoodExp'],$row['cOtherExp'])

However, I agree with @ErnieAlex, the database should be doing this work for you.

$sql = "SELECT custID, cID1, cFName, cLName, cPlanName, cTravel, cTravelExp, cLodgeExp, cFoodExp, cOtherExp, (cLodgeExp + cTravelExp + cFoodExp + cOtherExp) AS total FROM $tablename WHERE custID = ? AND cID1= ?"; 
$stmt = $conn->prepare($sql);
$stmt->execute([$custID, $cID1]);
$result = $stmt->fetchAll();

I will also point out that the data modeling and table design sucks. All of those columns should not be in the same table.

I would also use the actual table name rather than a variable. You don’t show how that is populated, but if you know the columns you want, that means you should know the exact table to question with the query.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service