0

I am getting error Undefined variable: con at line:

$filter_Result = mysqli_query($con,$query);

in this PHP file:

<?php require_once('../Connections/conexion.php'); 

if(isset($_POST['search']))
{
    echo "estoy filtrando";
    $valueToSearch = $_POST['valueToSearch'];
    // search in all table columns
    // using concat mysql function
    $query = "SELECT * FROM `tblusuario` WHERE CONCAT(`idUsuario`, `strEmail, `strNombre`) LIKE '%".$valueToSearch."%'";
    $search_result = filterTable($query);

    $totalRows_DatosConsulta = mysqli_num_rows($search_result);

}
 else {

     echo "estoy sin filtrar";

     $query = "SELECT * FROM `tblusuario`";
     $search_result = filterTable( $query );

     $totalRows_DatosConsulta = mysqli_num_rows( $search_result );
}


function filterTable($query)
{
    $filter_Result = mysqli_query($con,$query);
    return $filter_Result;
}
?>

Here is file conexion.php, where variable $con is defined:

$hostname_con = "p:localhost";
$database_con = "ondemand";
$username_con = "root";
$password_con = "";
$con = mysqli_connect($hostname_con, $username_con, $password_con, $database_con);
mysqli_set_charset($con, 'utf8');

I have checked if file conexion.php is found correctly, and it is loaded.

I am not able to find the reason for the error.

mvasco
  • 4,965
  • 7
  • 59
  • 120

2 Answers2

1

You need to use it like this

function filterTable($query)
{
    global $con;
    $filter_Result = mysqli_query($con,$query);
    return $filter_Result;
}

or you can pass the $con as argument while calling the function.

   function filterTable($con, $query)
    {
        $filter_Result = mysqli_query($con,$query);
        return $filter_Result;
    }

It is due to scope of variable in PHP.

Hari Lamichhane
  • 520
  • 5
  • 11
1
function filterTable($con, $query)
{
    $filter_Result = mysqli_query($con,$query);
    return $filter_Result;
}
Tkachenko
  • 25
  • 4