从mysql查询创建函数

时间:2018-01-26 11:32:52

标签: php mysql

我有一个特定的查询,正在阅读我的数据库中的5篇最新文章的类别(mysql专栏)" sport"

我想运行多个查询,一个用于运动,一个用于汽车,一个用于书籍等。而不是多次重写完整查询并用汽车/书籍等替换类别运动我想知道它是否可以将它重建为我输入类别的函数(如第2行中的sports),并输出字符串$ sports(如第10/11行),其中包含查询中定义的数据库中的所有检索。

// Build feed source for the latest News of Sport
$sqlCommand = "SELECT * FROM feeds where category like 'Sport' ORDER BY id DESC LIMIT 5"; 
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

$sport = '';
while ($row = mysqli_fetch_array($query)) { 
    $fid1 = $row["id"];
    $title1 = $row["title"];
    $description1 = $row["description"];
    $sport .= '<h2><b><a href="detail/' . $fid1 . '/' . $title1 . '" title="' . $title1 . '">' . $title1 . '</a></b></h2>';
    $sport .= '<a href="detail/' . $fid1 . '/' . $title1 . '" title="' . $title1 . '">' . $description1 . '</a><br/>';

} 
mysqli_free_result($query);

1 个答案:

答案 0 :(得分:0)

这就是我最终解决它的方式:

function nieuws ($category,$color) {

    global $myConnection;
    $sqlCommand = "SELECT * FROM feeds where category like '$category' ORDER BY id DESC LIMIT 1"; 
    $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 
    $output = '';
    $output = "<div class=headlines style=background:$color><a class=newslink href='$category'>$category</a></div>";
    while ($row = mysqli_fetch_array($query)) { 
        $fid1 = $row["id"];
        $title1 = $row["title"];
        $titleseo1 = seofy($title1);
        $description1 = $row["description"];
        $photo1 = $row["photo"];
        if ('' == $photo1) {$photo1='images/pic1.jpg';};
        $output .= "<div class=news2 style=background:#F0F8FF><img src='$photo1' alt='photo' style='width:200px;height:150px;object-fit:cover;border:0;margin:0px 5px 0px 0px;float:left'>"; //object-fit: cover zorgt dat het origineel het plaatje vult zonder distortion, is in principe cropping
        $output .= '<b><a href="detail/' . $fid1 . '/' . $titleseo1 . '" title="' . $title1 . '">' . $title1 . '</a></b></br>';
        $output .= '<a href="detail/' . $fid1 . '/' . $titleseo1 . '" title="' . $title1 . '">' . $description1 . '</a><br/>';
        $output .= "</div>";
        } 
        mysqli_free_result($query);
}