【问题标题】:How to make this function from while in php如何在php中创建此功能
【发布时间】:2015-11-17 04:09:06
【问题描述】:

我有这段代码,它从我的数据库中带来一个依赖于 id 的帖子

    global $connect;
    $id = $_GET['id'];
    $sql_query="SELECT * FROM `topics` WHERE id = {$id}";
    $result = mysqli_query($connect,$sql_query);
    while ($row = mysqli_fetch_assoc($result)) { ....}

我怎样才能使它成为函数(我的尝试):

Function get_single_post($id) {
    global $connect;
    $id = (int)$id;
    $sql_query="SELECT * FROM `topics` WHERE id = {$id}";
    $result = mysqli_query($connect,$sql_query);

    while ($row = mysqli_fetch_assoc($result)) {
        $post[] = $row;
    }
    return $post;
}

要使用这个功能,我用这个:

get_single_post($_GET['id']);

当我打电话给我使用的东西时: $post['title']; 标题为 ex

【问题讨论】:

  • 你得到什么错误信息?
  • 注意:未定义的变量:发布在 C:\xampp\htdocs\blog\topic.php 的第 33 行

标签: php function mysqli


【解决方案1】:

请记住,函数返回一个值,但该值必须分配给一个变量才能访问它。

$post = get_single_post($_GET['id]);

现在使用上述内容应该可以让您按预期访问帖子。

【讨论】:

    【解决方案2】:

    如果您的 id 是主键,则不需要 while 循环,因为它只会返回一个结果

    修改函数

    Function get_single_post($id) {
        global $connect;
        $id = (int)$id;
        $sql_query="SELECT * FROM `topics` WHERE id = {$id}";
        $result = mysqli_query($connect,$sql_query);    
    
        return mysqli_fetch_assoc($result);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多