I'm developing a system that takes the category IDs that are stored in the database, separated by ,
, I'm using explode
, turning them into a array
and then I'm using the array_rand()
to sort only one value of this array. Everything works perfectly, but now I need to get other records that contain the same category of this drawn. If the value returns false
(empty), I need to raffle again until I find a record with this category, so that the sidebar will not run out of records.
Viewing an ad
Pleasenote,forexample,inthisadthecategoriesareFoodandAttendant
IwantmysidebartofetchotheradsthatarethesamecategoryandwithORDERBYrand()
,seeanexampleofthesidebar.
The categories are stored in the database as follows:
anuc_cat_id = 1,7,2,9 | ID's das categorias
anuc_anu_id = 2 | Indica a qual anúncio corresponde
Category separation and draw
$categoriasAnuncioAtual = explode(',', $rowCategoriasAnuncioAtual->anuc_cat_id);
$categoriaRandomAtual = $categoriasAnuncioAtual[array_rand($categoriasAnuncioAtual)];
Querying in the database and checking
$selParecidos = $conn->prepare('SELECT * FROM anuncios a
INNER JOIN anuncios_categorias ac ON ac.anuc_anu_id = a.anu_id
INNER JOIN anuncios_fotos af ON af.anuf_anu_id = a.anu_id AND af.anuf_posicao = ?
INNER JOIN usuarios u ON a.anu_usu_id = u.usu_id
WHERE a.anu_url <> ? AND a.anu_status = ? AND a.anu_status_adm = ?
GROUP BY anu_id
ORDER BY rand()');
$selParecidos->execute(array(0, $rowId->anu_url, 1, 1));
$rowParecidos = $selParecidos->fetch(PDO::FETCH_OBJ);
$arraycategoriasbanco = explode(',', $rowParecidos->anuc_cat_id);
//busca pelo array random dentro da variavel de categorias do anuncio
if(in_array($categoriaRandomAtual, $arraycategoriasbanco)){
echo "existe";
}
In the last lines of the code where it follows if(in_array())
I need that if it does not exist, make a new SELECT
until I find a record that corresponds to this if()
. ?
I have no errors in SELECT or too much, I just need a way to re-run the select if
if(in_array())
is empty. I thought about doingfunction()
but I can not do it.