开发者

Generating news from db table

I'm trying to generate news from db table.

My table look like that

Generating news from db table

And the function that generated news from db table

function generateNews ($lang, $db)
{
    $title = 'title_' . $lang;
    $short = 'short_' . $lang;
    $detailed = 'detailed_' . $lang;
    $result=$db->query("SELECT id, $title as title, $short as short, $detailed as detailed, ndate FROM news");

    while($row=$result->fetch_object()) {
        $title=makeEntry ('title', $row->title);
        $stitle=makeEntry ('stitle', $row->short);
        $content=makeEntry ('content',$row->detailed);
        $footer=makeEntry ('footer',$row->ndate);

        echo makeEntry ('entry',$title.$stitle.$content.$footer);
    }   
}   

function makeEntry ($part,$data)
{
    if($part=='title')
        return '<h3 class="entry-header">'.$data.'</h3>'."\n";
    else if ($part=='stitle')
        return '<h4 class="entry-stitle">'.$data.'</h4>'."\n";
    else if ($part=='content')
        return '<div class="entry-content"><p>'.$data.'</p></div>'."\n";
    else if ($part=='footer')
        return '<div class="entry-footer">'.$data.'</div>'."\n";
    else if ($part=='entry')
        return '<div class="entry">'.$data.'</div>'."\n";
}

It works, but this code is very simple so I feel like it could be shortened. Any suggestions?

BTW. D开发者_如何学Pythonon't post about sql injection holes. I already whitelisted table column names


Using a switch case control structure would get you rid of these elseif ($part == )statements.


Here's another possible solution:

function makeEntry($part,$data)
{
    $results = array( 'title' => '<h3 class="entry-header">'.$data.'</h3>'."\n",
                      'stitle' => '<h4 class="entry-stitle">'.$data.'</h4>'."\n",
                      //etc etc....
                     );
    return $results[$part];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜