简体   繁体   中英

How am I supposed to store a value from my database as a variable in php using PHP and SQL?

I would like to see where my code is incorrect. I want to store values from my database as a php array. Then I'd like to store the individual parts of the array as separate variables. Here is my code:

<?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];
?>

This will run your mysql query and add each comment to an array of comments, then print the array.

   <?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);

    ?>

not sure if you are in console or through web server.

<?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';
}
?>

this is called a loop. loop is your friend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM