doutiao2540 2012-10-13 19:50
浏览 52

使用mysqli创建一个从表返回X行数的函数?

I am new to functions so to learn about them I have been converting a website I made to use functions. I want to be able to use the function for other sites, so I am hoping to pass all the table/query information to the function, then return the posts in arrays or something similar so I can style them however needed once the function has passed the info back. I have achieved this with a single post, but can't get it to work with multiple posts. I will usually be retreiving about 10 rows, at the moment with 4 columns.

Here is my single post function

   function readPostByID($postID, $table) {
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if (mysqli_connect_errno()) {
        return false;
    }
    if ($result = $mysqli->query("SELECT * FROM '$table' WHERE id = '$postID'")) {
        while($row = $result->fetch_array()) {
            $time1 = date('H:i \o
 jS M Y', $row['publishedtime']);
            $postarray['1'] = $row['title'];
            $postarray['2'] = $row['content'];
            $postarray['3'] = $row['author'];
            $postarray['4'] = $time1;
        }
        $result->close();
    }
    mysqli_close($mysqli);
    return $postarray;
}

Any help to switching this to retreive multiple posts would be appreciated

Thanks

  • 写回答

1条回答 默认 最新

  • doujieju0397 2012-10-13 21:05
    关注

    The first change would be to select a range of ids, which you can do like this:

     WHERE id in (1,2,3,4,5)
    

    You're already looping across the results, but you'll need a better data structure to store them in.

    The other suggestions to use LIMIT and offset are good if you're doing paging.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测