Stefan Stefan - 7 months ago 14
PHP Question

How to SELECT all the tables mySql of a db and show query order by data, tables have the same structure

I want to make a newsbar show i need to show the last 5 query,
I have 5 categories(tables) like history, nature, lifestyle, science and travel in the same database mySql
all the tables have the same structure
id, title, descriere, data, picture, alt, approved and I want to selet the last 5 order by data, How i can do this? and the php code to show the query

my code for a show the last 5 query order by data in the same tables is this...

$sql = "SELECT id, titlu, link, poza, alt FROM istorie WHERE approved='1' ORDER BY RAND() LIMIT 3";
$query = mysqli_query($db_conx, $sql);
$istorielist = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$titlu = $row["titlu"];
$link = $row["link"];
$poza = $row["poza"];
$alt = $row["alt"];
$istorielist .= '<div id="articol-content-more"><a href="/istorie/'.$link.'"><img src="/images/'.$poza.'.jpg"class="articol-content-more-image" alt="'.$alt.'"><p class="articol-content-more-title">'.$titlu.'</p></a><span><a class="articol-content-more-afla" href="/istorie/'.$link.'">Citește mai multe</a></span><span class="articol-content-more-fl"><div class="fb-share-button" data-layout="button_count" data-href="http://esticurios.ro/istorie/'.$link.'"></div></span></div>';
}
?>
<p class="moreArticle">Mai multe articole:<br>
<?php echo $istorielist;?> <br>
<?php mysqli_close($db_conx);?>

Answer

You can take category array static Or put all categories into one table and make category array dynamically also

<?
$catArray = array("history","nature", "lifestyle", "science","travel");    
$istorielist = '';
foreach($catArray as $k=>$v)
{    
    $sql = "SELECT id, titlu, link, poza, alt FROM ".$v." WHERE approved='1' ORDER BY RAND() LIMIT 3";
    $query = mysqli_query($db_conx, $sql);   
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        $id = $row["id"];
        $titlu = $row["titlu"];
        $link = $row["link"];
        $poza = $row["poza"];
        $alt = $row["alt"];
        $istorielist .= '<div id="articol-content-more"><a href="/istorie/'.$link.'"><img src="/images/'.$poza.'.jpg"class="articol-content-more-image" alt="'.$alt.'"><p class="articol-content-more-title">'.$titlu.'</p></a><span><a class="articol-content-more-afla" href="/istorie/'.$link.'">Citește mai multe</a></span><span class="articol-content-more-fl"><div class="fb-share-button" data-layout="button_count" data-href="http://esticurios.ro/istorie/'.$link.'"></div></span></div>';
    } 
}

?>


Comments