将多个查询调用为一个

时间:2015-06-24 14:03:50

标签: php mysql

我对数据库中的单个表有两个查询,唯一的区别是限制。我喜欢输出,但我知道必须有更实际的方法来做到这一点。有谁能提出建议?

$sql1 = mysql_query("SELECT * FROM products ORDER BY id DESC LIMIT 20");
$count = mysql_num_rows($sql1);
if ($count > 0) {
    while($row = mysql_fetch_array($sql1)){ 
}
}

$sql2 = mysql_query("SELECT * FROM products ORDER BY id DESC LIMIT 1");
$count = mysql_num_rows($sql2);
if ($count > 0) {
    while($row = mysql_fetch_array($sql2)){ 
}
}

2 个答案:

答案 0 :(得分:0)

创建一个函数并将限制作为参数传递:

function doQuery($limit = 1) {
    $sql = mysql_query("SELECT * FROM products ORDER BY id DESC LIMIT $limit");
    $count = mysql_num_rows($sql);
    if ($count > 0) {
        while($row = mysql_fetch_array($sql)){ 

        }
    }
};

doQuery(1);
doQuery(20);

答案 1 :(得分:0)

$sql1 = mysql_query("SELECT * FROM products ORDER BY id DESC LIMIT 20");
$count = mysql_num_rows($sql1);
if ($count > 0) {
    while($row = mysql_fetch_array($sql1)){
        //loop over all records...
    }
}

$count = mysql_num_rows($sql1);
if ($count > 0) {
    if($row = mysql_fetch_array($sql1)){ 
        //retrieve one record
    }
}