Mysql and php dates

3

I need to bring some data from a person table, especially the birth field, but I need at birth to only show me the year and I can not do it, it throws me empty. How else can the problem be solved?

Note: Placing only the query to test it on phpmyadmin works, but when I add it to the function it does not.

Code of the function with the query

	public static function getById2($idPersona){
		 $sql = "select documento, nombre1, nombre2, apellido1, apellido2, EXTRACT(YEAR FROM nacimiento) from ".self::$tablename." where idPersona=$idPersona";
		$query = Executor::doit($sql);
		return Model::one($query[0],new personaData());
	}

Result

The Model class

<?php
class Model {

	public static function exists($modelname){
		$fullpath = self::getFullpath($modelname);
		$found=false;
		if(file_exists($fullpath)){
			$found = true;
		}
		return $found;
	}

	public static function getFullpath($modelname){
		return "core/app/model/".$modelname.".php";
	}

	public static function many($query,$aclass){
		$cnt = 0;
		$array = array();
		while($r = $query->fetch_array()){
			$array[$cnt] = new $aclass;
			$cnt2=1;
			foreach ($r as $key => $v) {
				if($cnt2>0 && $cnt2%2==0){ 
					$array[$cnt]->$key = $v;
				}
				$cnt2++;
			}
			$cnt++;
		}
		return $array;
	}
	//////////////////////////////////
	public static function one($query,$aclass){
		$cnt = 0;
		$found = null;
		$data = new $aclass;
		while($r = $query->fetch_array()){
			$cnt=1;
			foreach ($r as $key => $v) {
				if($cnt>0 && $cnt%2==0){ 
					$data->$key = $v;
				}
				$cnt++;
			}

			$found = $data;
			break;
		}
		return $found;
	}

}
?>
    
asked by Horus 04.04.2018 в 20:31
source

1 answer

1

You could do it in two ways in the query or in the code.

To do it in the query you could write your code like this:

    $sql = "SELECT documento, nombre1, nombre2, apellido1, apellido2, YEAR(nacimiento) as anio FROM ".self::$tablename." where idPersona=$idPersona"

YEAR (birth) is the MySQL function that gets the date of birth to variables type DATE or DATETIME, if the variable is not of any of these types, it will not work

To do it in the code, the easiest way would be to explode the result of the query and grasp the value of the year, something similar to this:

<?php
    $lstrFecha = '2018-10-22';
    $larrFecha = explode('-',$lstrFecha);
    echo $larrFecha[0];
?>
    
answered by 04.04.2018 в 21:46