Getting values from JSONarray

67 views Asked by At

I am writing a PHP script which

  1. connects to the database

  2. fetches all orders in an array. ($result)

  3. I want to go through the array and fetch all say "userName"

The trouble is, with my code below, I am able to only get the first character of each "userName" in the array.I want an array with all "userName"s.

<?php

$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$dbname = 'dbname';

//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$sql = "select * from ordertest";

$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
$result = mysqli_fetch_array($retval, MYSQLI_ASSOC);

if (mysqli_num_rows($retval) > 0) {
    $arr = json_decode($result, true);

    foreach ($result as $key => $value) {
        echo $value["userName"];
    }
} else {
    echo $sql;
}
1

There are 1 answers

4
Slava Rozhnev On BEST ANSWER

The solution should be next:

<?php

    $sql = "select * from ordertest";

    // retrieve query result from DB
    $retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
    
    // if result not empty
    if (mysqli_num_rows($retval) > 0) {

        // retrieve single row from $retval
        while ($result = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
            echo $result["userName"];
            echo "\n";
        }
    } else {
        echo $sql;
    }

Look example here: PHPize.online