0

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;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
sat
  • 3
  • 3
  • Well, you've got quite the mash of code there. First tip: `$result` is an object, and not a json string to decode. – IncredibleHat Aug 28 '20 at 17:46
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Aug 28 '20 at 19:31

1 Answers1

0

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
  • Well, OK, the `or die()` part should have been left out but otherwise I think this answer delivers exactly what OP was looking for. Why the downvote? – Carsten Massmann Aug 29 '20 at 22:05
  • 1
    This piece of code not looks as production ready, so I mean `die()` is legitimate for debug, also as `echo $sql;`. Sure it must be removed in production – Slava Rozhnev Aug 29 '20 at 22:26
  • Hello Slava .Thanks for taking the time to help. The output echoed ($result["userName"];) looks like it is an object. I want it to be an array to pass it to a jqgrid.How can we echo as an array of objects( $result)? – sat Aug 30 '20 at 09:22
  • @sat Please update your question and post desired data format – Slava Rozhnev Aug 30 '20 at 09:24