0
The scenario is simple, SQL displays all the criteria results and there is a filter to select multi values that will be passed to SQL, which should refer to tbl2
in the field tbl2_criterio
, and thus display only records that contain values equal to filter values.
I tried to accomplish in the $where_filtro
the use of "AND tbl2_criterio = '" . $var_filtro[0] . "'
and the others, but it didn’t work.
How to check the records on tbl2
in the field tbl2_criterio
and adapt to SQL?
Follow down what I’ve tried so far:
<?php
$where_filtro = ""; // Vazio na QUERY se $_GET['var_filtro'] não foi definido.
if( isset( $_GET['var_filtro'] ) {
$var_filtro = $_GET['var_filtro'];
$var_filtro = explode(",",$var_filtro);
// Imprime:
// $var_filtro[0] = "valor1";
// $var_filtro[1] = "valor2";
// $var_filtro[2] = "valor2";
for($i=0;$i<=count($_GET['var_filtro']);$i++) {
$where_filtro .= " AND `tbl2_criterio` = '" . mysqli_real_escape_string($conn,$var_filtro[$i]) . "' ";
}
}
$sql = "SELECT
*
FROM
`tbl1`
INNER JOIN
`tbl2`
ON
`tbl2_id_pai` = `tbl1_id`
WHERE
`tbl1_status` = 'A'
" . $where_filtro . "
;";
$query = mysqli_query( $conn, $sql );
while( $row = mysqli_fetch_array( $query, MYSQLI_ASSOC ) {
echo $row['tbl1_row1']."<br>\n";
}
?>
SQL looks like this after running when I echo into $sql.
SELECT
*
FROM
`tbl1`
INNER JOIN
`tbl2`
ON
`tbl2_id_pai` = `tbl1_id`
WHERE
`tbl1_status` = 'A'
AND
`tbl2_criterio` = 'valor1'
AND
`tbl2_criterio` = 'valor2'
AND
`tbl2_criterio` = 'valor3';
Query returns: Mysql did not return any record. (Query took 0.0013 seconds.).
But there are values in the records and they are related to the record of tbl1.
AND tbl2_criterio . It would not be AND tbl2.criterio ?
– Sr. André Baill
No, that’s right, the field is named tbl2_criterio, tbl2 is the table and tbl2_criterio is the table field, so it is easy to find in the code.
– ElvisP
Okay but then it wouldn’t be tbl2.tbl2_criterio?
– Sr. André Baill
Yes, it would be so if there were alias
– ElvisP
I think I understand.
– Sr. André Baill
Before you execute the query, what about your SQL? Already with the
where
added?– Matheus Ribeiro
I added $sql printed. grateful!
– ElvisP
The tables were missing... tbl1. and tbl2. try the way I showed you
– Sr. André Baill