In general terms, the functions need to receive in parameter all those values with which they will work ... or no parameter if everything necessary is within the scope of the function. And, if necessary, they will return the expected value.
In this case, we assume that at least the value $fila
is obtained outside the function. Then we passed it in parameter so that the function works with that information. Notice that I have created a value $calculo
, which will change according to the value of $periodo
and at the end of if
, we make the calculation with the corresponding value. Thus, we saved several lines of code, winning in simplicity and clarity in the program ... Finally, it will return ( return
), the final data.
For example:
/*
*Vamos a suponer que la consulta se hace desde otra parte
*Aunque puedes hacer esto dentro de la función,
*todo dependerá de tu conexto
*/
$list = $conn->query("SELECT * FROM cuenta WHERE useride = '".$code."' AND estado = 0");
$fila = $list->fetch();
/*
*Ahora le pasas $fila a la función
*como es una función que tiene un return, puedes asignar el resultado
*de la llamada de la función a una variable
*/
$fechaVencimiento=getVencimiento($fila);
echo $fechaVencimiento;
/*
*Esta es la función y el parámetro que recibe
*/
function getVencimiento($fila){
$periodo = $fila['periodo'];
if ($periodo == 'mensual') {
$calculo='+30 day';
} elseif ($periodo == 'semestral') {
$calculo = '+180 day';
} else {
$calculo = '+365 day';
}
$fecha = $fila['fechapago'];
$nfecha = strtotime ($calculo , strtotime ($fecha)) ;
$nfecha = date ('d-m-Y' , $nfecha);
/*
*Como verás, he quitado todos los echo
*porque interesa que la función retorne el valor sólo al final
*/
return $nfecha;
}
A more elegant way
In some cases, the code is clearer and more elegant if we use a block switch
The case that you expose is perfect to use it. The function would look like this:
function getVencimiento($fila){
$periodo = $fila['periodo'];
switch ($periodo) {
case 'mensual':
$calculo='+30 day';
break;
case 'semestral':
$calculo = '+180 day';
break;
default:
$calculo = '+365 day';
}
$fecha = $fila['fechapago'];
$nfecha = strtotime ($calculo , strtotime ($fecha)) ;
$nfecha = date ('d-m-Y' , $nfecha);
return $nfecha;
}
IMPORTANT NOTE ABOUT SECURITY:
The query SELECT * FROM cuenta WHERE useride = '".$code."' AND
estado = 0
is vulnerable to SQL injection. To correct that serious
security problem, you should implement the use of queries
prepared. For more information you can read:
How to avoid SQL injection in PHP?