0

I use the following PHP lines to query data from a MySQL table. I want to store the query results in an array and then later on the same page print specific values from this array based on their ID.

I am new to PHP and hope someone can help me with an explanation on what I am doing wrong or missing here. I am assuming I create the array wrongly.

My PHP (relevant part, variables are defined earlier on this page):

$con = mysqli_connect($host_name, $user_name, $password, $database);
$result = mysqli_query($con, "SELECT id, $col FROM $table ORDER BY id");
$rows = array();

if($result)
{
    while($row = mysqli_fetch_array($result))
    {
        print_r($row);
    } 
}
var_dump($rows);

My current array (when printed as above):

Array ( [0] => testid1 [id] => testid1 [1] => testval1 [en] => testval1 ) Array ( [0] => testid2 [id] => testid2 [1] => testval2 [en] => testval2 ) Array ( [0] => testid3 [id] => testid3 [1] => testval3 [en] => testval3 ) array(0) { }

Example:
E.g. I want to print the value for the item with ID = "testid2" from this array. In this case the printed value should be "testval2".

Many thanks in advance, Mike

3
  • print_r doesn't create an array, it outputs all values in an array or object. Change to $rows[] = $row; inside your while. ... or simply use php.net/manual/en/mysqli-result.fetch-all.php. Commented Sep 21, 2019 at 18:35
  • @user3783243: Thank you. Do you have an example or a link to show me how to create the array and how to print a value from it ? Commented Sep 21, 2019 at 18:37
  • print_r($set['1']); ? print_r($set['1']['id']); ? Commented Sep 21, 2019 at 20:31

3 Answers 3

1

Store your data as:

for
(
    $set = array(); 
    $row = $result->fetch_assoc(); 
    // use value of `id` as the key in your `$set`
    $set[$row['id']] = $row
);
print_r($set);

// later:
$id = 1;
echo $set[$id]['en'];
// or
echo $set[$id][$lang];
Sign up to request clarification or add additional context in comments.

Comments

0

You can just use fetch_all() and then column search

$con = mysqli_connect($host, $username, $password, $database);
$result = mysqli_query($con, "SELECT id, $lang FROM $table ORDER BY id");
$set = $result->fetch_all(MYSQLI_ASSOC);

$key = array_search('testid2', array_column($set, 'id'));

echo $set[$key]['en'];

Comments

0

You can use array_combine() with array_column() to convert the query output (in rows and columns) to key-value format (key being the id, and value being the en column):

// $set array is populated using fetch_assoc
// create a new array using $set
$modified_set = array_combine(array_column($set, 'id'), 
                              array_column($set, 'en'));

// Now, you can access the en value for a specific id like this:
// eg: for id = testid2
echo $modified_set['testid2']; // will display testval2

Comments