I have a table in HTML where the information I have stored in a table of my Mysql database is displayed and this information is consulted through ajax. At first I had a code that extracted and showed all the data without having any search option. But now I have wanted to make some changes and put some search filters so that the user can have different personalized query options. The problem is that when trying to arm the sql code and execute it, it returns the following error:
Fatal error: Uncaught Error: Call to a member function fetch_object () on boolean in C: \ xampp \ htdocs \ Fiverr3 \ fiverr_work2 \ driver \ DataController.php: 91 Stack trace: # 0 {main} thrown in C: \ xampp \ htdocs \ Fiverr3 \ fiverr_work2 \ driver \ DataController.php on line 91
Apparently the problem is in the following code that is responsible for putting together the query:
$nombre = ["nombre_apellido", "Sin Nombre"];
$dni = ["dni", ""];
$sexo = ["sexo", "Masculino"];
$email = ["email", ""];
$importar = ["importar", ""];
$tipo = "hotmail";
$fecha1 = "";
$fecha2 = "";
$request = "SELECT * FROM tabla2";
$objDataTipo = new Data();
if($nombre[1] == "" && $dni[1] == "" && $sexo[1] == "" && $email[1] == "" && $fecha1 == "" && $fecha2 == "" && $importar[1] !== "")
{
//extraer data
$request = "SELECT * FROM tabla2 ORDER BY id DESC";
}
else
{
$arrays = [$nombre, $dni, $email, $sexo, $importar];
$request .= "WHERE ";
for($i = 0; $i < count($arrays); $i++)
{
if($i !== 4)
{
if ($arrays[$i][1] !== "")
{
$request .= $arrays[$i][0] . " = '". $arrays[$i][1] . "' AND ";
}
}
else
{
if ($arrays[$i][1] !== "")
{
$request .= $arrays[$i][0] ." = ". $arrays[$i][1] . " AND";
}
}
}
if ($fecha1 !== "" && $fecha2 == "")
{
$request .= " fecha >= '" . $fecha1 ."'";
}
if ($fecha1 == "" && $fecha2 !== "")
{
$request .= " fecha <= '" . $fecha2 ."'";
}
if ($fecha1 !== "" && $fecha2 !== "")
{
$request .= " fecha BETWEEN '". $fecha1."' AND '" . $fecha2 . "' ";
}
$request = trim($request, " ");
$request = trim($request, "AND");
$request = trim($request, " ");
$request .= " ORDER BY id DESC";
}
$objDataTipo = new Data();
$query = $objDataTipo->FiltroDeBusqueda($request);
$data = Array();
$i = 1;
$status = "";
while ($fetch = $query->fetch_object())
{
echo $fetch->nombre_apellido;
echo "<br>";
echo $fetch->dni;
echo "<br>";
echo $fetch->email;
echo "<br>";
}
This is the function that executes the query
public function FiltroDeBusqueda($sql)
{
global $conexion;
$query = $conexion->query($sql);
return $query;
}
I do not know exactly where the code is failing. The idea is that if the user does not select any option he will show all the stored data without doing this filtering. But if you select one of the filtering options, it will return the data correctly.