Evilnapsis

Programming, Hacking and More

PHP Stuffs

Paginacion de Calendario por Mes con PHP

Vamos a crear un calendario con PHP en HTML y agregaremos una paginacion para cada mes con botones para navegar anterior y siguiente.

Anteriormente habiamos creado un calendario con PHP y HTML y lo renderizabamos con un formulario para seleccionar el mes y el año.

Usaremos el codigo similar para generar el calendario, solo cambiara que se removera el formulario y se agregaran los botones de anterior y siguiente.

El boton de anterior retrocedera al mes anterior del mismo año,pero si esta en ENERO retrocedera a DICIEMBRE del año anterior.

El boton de siguiente avanzara un mes del mismo año. Si estamos en DICIEMBRE entonces avanzaremos a enero del año siguiente.

Codigo

La primera parte del codigo es para definir la fecha inicial.

Tambien definimos cuando estamos en otra fecha, obtenemos el mes y año usango GET.

Y creamos las URL para los botones de Anterior y Siguiente.

<?php
$start_date = date("Y")."-".date("m")."-01";
$current_year = date("Y");
$current_month = date("m");
$start = strtotime($start_date);
if(isset($_GET["m"]) && isset($_GET["y"]) && $_GET["m"]!="" && $_GET["y"]!=""){
$start = strtotime($_GET["y"]."-".$_GET["m"]."-01");

$current_year = $_GET['y'];
$current_month = $_GET["m"];
}
echo "<h2>".date("F, Y", $start)."</h2>";

	$prev_month = $current_month-1;
	$prev_year = $current_year ;
	$next_month = $current_month+1;
	$next_year = $current_year ;	


if($current_month=="01"){
	$prev_month = 12;
	$prev_year = $current_year -1;
}else if($current_month==12){
	$next_month = 1;
	$next_year = $current_year +1;	
}
$prev_url = "index.php?m=$prev_month&y=$prev_year";
$next_url = "index.php?m=$next_month&y=$next_year";

?>

La siguiente parte del codigo es codigo HTML mezclado con PHP para renderizar la tabla con el calendario y los botones de paginacion Anterior y Siguiente.

<a href="<?php echo $prev_url; ?>">Anterior</a>
<a href="<?php echo $next_url; ?>">Siguiente</a>

<table border="2">
	<thead>
		<th>Domingo</th>
		<th>Lunes</th>
		<th>Martes</th>
		<th>Miercoles</th>
		<th>Jueves</th>
		<th>Viernes</th>
		<th>Sabado</th>
	</thead>
<?php 
$index = 0;
$startpos =0; 
$continue2 = 1;
for($i=1; $i<=6; $i++): $index++; ?>
	<tr>
		<?php for($j=0; $j<7; $j++):?>
			<td>
			<?php if($startpos>0 && $continue2<date("t", $start)){ $continue2++; echo "<h4>".$continue2."</h4>"; }?>
				<?php if($i==1 && $j==date("w", $start)):?>
					<h4>1</h4>
				<?php 
				$startpos=$index;
			endif; ?>
			</td>
		<?php endfor;?>
	</tr>
<?php endfor; ?>
</table>

Y listo, solo falta agregar el codigo al archivo index.php y ejecutar.

Resultado

El resultado es el siguiente.

Listo.

Happy Coding.

Agustin Ramos

Desarrollador de Software

Leave a Reply