【问题标题】:How am I supposed to store a value from my database as a variable in php using PHP and SQL?我应该如何使用 PHP 和 SQL 将数据库中的值作为变量存储在 php 中?
【发布时间】:2025-11-24 18:00:01
【问题描述】:

我想看看我的代码在哪里不正确。我想将数据库中的值存储为 php 数组。然后我想将数组的各个部分存储为单独的变量。这是我的代码:

<?php
    $result = mysqli_query($db, "SELECT column FROM table");
    if (!$result) {
        echo 'Could not run query';
        exit;
    }
    $comments = mysqli_fetch_row($result);
    $comment0 = $comments[0];
    $comment1 = $comments[1];
    $comment2 = $comments[2];
    $comment3 = $comments[3];
    $comment4 = $comments[4];
    $comment5 = $comments[5];
    $comment6 = $comments[6];
    $comment7 = $comments[7];
    $comment8 = $comments[8];
    $comment9 = $comments[9];
?>

【问题讨论】:

  • 你当前的代码有什么问题?
  • 您是否要遍历结果?或者您是否尝试将每个结果指定为以后可以在其他地方使用的变量?

标签: php arrays phpmyadmin


【解决方案1】:

这将运行您的 mysql 查询并将每个注释添加到 cmets 数组中,然后打印该数组。

   <?php
        $result = mysqli_query($db, "SELECT column FROM table");
        if (!$result) {
            echo 'Could not run query';
            exit;
        }
        $comments = array();
        while($comment = mysqli_fetch_row($result)){
            $comments[] = $comment;
        }
        print_r($comments);

    ?>

【讨论】:

    【解决方案2】:

    不确定你是在控制台还是通过网络服务器。

    <?php
        $result = mysqli_query($db, "SELECT column FROM table");
        if (!$result) {
            echo 'Could not run query';
            exit;
        }
        $comments = mysqli_fetch_row($result);
    
    foreach($comments as $comment){
        echo print_r($comment,1).'--------------\r\n<br>\r\n';
    }
    ?>
    

    这称为循环。循环是你的朋友。

    【讨论】:

      最近更新 更多