Here is an example using BETWEEN and improving code security through prepared queries:
VIEW DEMO
<?php
require "util/public_db_info.php";
$pdo = new PDO($dsn, $user_name, $pass_word);
$fecha1="1970-01-01";
$fecha2="1999-12-31";
//Uso de consultas preparadas para evitar la Inyección SQL.
$sql = "SELECT * FROM persona WHERE fecha_nacimiento BETWEEN :inicio AND :fin;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":inicio",$fecha1);
$stmt->bindValue(":fin",$fecha2);
$stmt ->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($arrDatos)
{
echo "<pre>";
echo "CONSULTA 1: SE ENCONTRARON ".count($arrDatos). " REGISTROS\n";
print_r($arrDatos);
$strLista="\n\nLISTA DE DATOS CONSULTA 1:\n";
foreach ($arrDatos as $row)
{
$strLista.= "id: ".$row["persona_id"]." nombre: ".$row["persona_nom"].
" fecha: ".$row["fecha_nacimiento"]."\n";
}
echo $strLista;
echo "</pre>";
}
else
{
echo "No hay datos";
}
$sql = "SELECT * FROM persona;";
$stmt = $pdo->prepare($sql);
$stmt ->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($arrDatos)
{
echo "<pre>";
echo "\nCONSULTA 2 TODOS LOS DATOS: SE ENCONTRARON ".count($arrDatos). " REGISTROS\n";
print_r($arrDatos);
$strLista="LISTA DE DATOS CONSULTA 2:\n";
foreach ($arrDatos as $row)
{
$strLista.= "id: ".$row["persona_id"]." nombre: ".$row["persona_nom"].
" fecha: ".$row["fecha_nacimiento"]."\n";
}
echo $strLista;
echo "</pre>";
}
else
{
echo "No hay datos";
}
$pdo = null;
?>
Result
CONSULTA 1: SE ENCONTRARON 2 REGISTROS
Array
(
[0] => Array
(
[persona_id] => 1
[persona_nom] => Santiago
[fecha_nacimiento] => 1974-01-14
)
[1] => Array
(
[persona_id] => 2
[persona_nom] => Pedro
[fecha_nacimiento] => 1972-08-22
)
)
LISTA DE DATOS CONSULTA 1:
id: 1 nombre: Santiago fecha: 1974-01-14
id: 2 nombre: Pedro fecha: 1972-08-22
CONSULTA 2 TODOS LOS DATOS: SE ENCONTRARON 3 REGISTROS
Array
(
[0] => Array
(
[persona_id] => 1
[persona_nom] => Santiago
[fecha_nacimiento] => 1974-01-14
)
[1] => Array
(
[persona_id] => 2
[persona_nom] => Pedro
[fecha_nacimiento] => 1972-08-22
)
[2] => Array
(
[persona_id] => 3
[persona_nom] => Juan
[fecha_nacimiento] => 2002-04-10
)
)
LISTA DE DATOS CONSULTA 2:
id: 1 nombre: Santiago fecha: 1974-01-14
id: 2 nombre: Pedro fecha: 1972-08-22
id: 3 nombre: Juan fecha: 2002-04-10