I just asked a question earlier, but now i have formatted it into a function that does not return any value.
This is my code:
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data;
}
Now, i do know that mysql_
functions are depreciated, but its required for this application at the moment.
My current problem is that this function does not return anything after using GET parameters to test.
Any solutions to this?
EDIT
I have changed the last lines to: return json_encode($Data);
and now the screen shows: {"0":"8","SUM(TotalHrs)":"8"}
Always check that mysql_query()
has not returned an error! Specially if you are building your query from parts generated from inputs that may or may not be present.
This should at least identify any errors in the SQL.
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
if ( ! $Query ) {
// just debug code, should be amended for a live site situation
echo mysql_error();
return 'Its broken';
}
$Data = mysql_fetch_array($Query);
return $Data;
}
I figured out that the data i get returned was an array by doing echo json_encode(GetHours($UID, $DAY, $MONTH, $YEAR));
My finished code that works:
<?php
include 'assets/db_connect.php';
//Function to get total from WorkLog:
$DAY = $_GET['day'];
$MONTH = $_GET['month'];
$YEAR = $_GET['year'];
$UID = $_GET['id'];
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
}
else{
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
}
else{
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
}
else{
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs) FROM WorkLog WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data['SUM(TotalHrs)'];
}