user9419091
user9419091

Reputation:

Store Mysql rows in Array

I was wondering how I can store values in an Array, because I can just echo the $row['Name'], but if I want to store multiple values in array I get nothing.

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

if (!$conn) {
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

$sql = "SELECT * FROM " . $dbname . " WHERE id ='$id'";

$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)) {

    $thisArray[] = array( $row['Name'],$row['accountNumber']);
}

echo $thisArray[0];

Upvotes: 0

Views: 62

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

As you just want to load the results of a SQL statement into an array, you can use mysqli_fetch_all() and just fetch the columns you need.

When outputing the results, arrays should be output with something like print_r()...

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

if (!$conn) {
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

$sql = "SELECT Name,accountNumber FROM " . $dbname . " WHERE id ='$id'";

$query = mysqli_query($conn, $sql);
$thisArray = mysqli_fetch_all($query, MYSQLI_ASSOC);
print_r( $thisArray[0]);

Update: If you want to re-arrange the array to key by one of the columns, array_column() can do this...

$thisArray = array_column($thisArray, 'accountNumber', 'Name');

Upvotes: 2

Vaios P.
Vaios P.

Reputation: 404

You have to initialize your array outside of the loop first and when you echo it you don't need to specify a key except if you need a specific key. Based on your code above:

$thisArray = [];
while ($row = mysqli_fetch_array($query)) {
    $thisArray[] = [
        $row['Name'],
        $row['accountNumber']
    ];
}

echo $thisArray;

Upvotes: 0

Related Questions