Search code examples
phpmysqlsqldrupal-7

MySQL query from PHP returns incorrect results


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


Solution

  • ->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.