1

My MySQL table "tracks" has these two fields:

Id (Int)
Name (Varchar 255)

The values are:

1   Day 1
2   Day 2
3   Day 3

I am trying to retrieve all the tracks from PHP using this functions:

function getTracks() {
    $query = sprintf('select * from tracks');
    return contentRetrieverDataBaseQuery($query)->fetchAssoc();
}

function contentRetrieverDataBaseQuery($query) {
    $settings = contentRetrieverGetSettings();
    Database::addConnectionInfo('contentRetriever', 'default', $settings['database_connection']);
    db_set_active('contentRetriever');
    $result = db_query($query);
    db_set_active();
    return $result;
}

Running select * from event_tracks on phpmyadmin I get the results correctly.

When I do this:

$tracks = getTracks();
foreach ($tracks as $track) {
  echo $track['name'];
}

I get as an output "1D", which is the Id and the first letter of the Name.

What am I doing wrong?

EDIT: Corrected the name of the database

7
  • nowhere inside your contentRetrieveDataBaseQuery do you define $result... Commented May 19, 2015 at 19:12
  • @MarcB $result = db_query($query); Commented May 19, 2015 at 19:14
  • @camil: remind me to go see my optometrist... Commented May 19, 2015 at 19:15
  • 2
    Ok, now that my eyes are open, most likely the ->fetchAssoc() is returning a SINGLE row of data, which means that $tracks is a single level array, and $track['name'] is taking the string value in $track and trying to treat it as a string, meaning $foo = 'bar'; echo $foo[1] outputs a. - ['name'] will be parsed down to [0]. Commented May 19, 2015 at 19:17
  • 1
    Use fetchAll instead of fetchAssoc to get all the results as a multi-dimensional array. Commented May 19, 2015 at 19:19

1 Answer 1

1

->fetchAssoc() invariably returns a single row of query results, meaning that your array is a single record, and your loop will be putting that row's string values into $track. You then use $track as if it was an array, producing the following code equivalent:

$arr = array('abc', 'def'); // your one row of query results.
foreach($arr as $value) {
   // $value is now 'abc';
   echo $value['name']; // parsed/executed as $value[0];
  // output is 'a'
}

Strings can be treated as arrays of characters, which is why PHP didn't complain about $tracks['name']. It simply treated as ['name'] as a goofy attempt at using a non-numeric array index, and converted it to 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.