1

I trying to insert SQL query results to PHP array:

$sql= $conn -> prepare("SELECT top(10) code, name, SUM(minutes)as total  FROM db_name group by code, name ORDER BY total desc");
$sql -> execute();

$combinedResults = array();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC)) {
    $combinedResults[$row['code']][] = array( 
    'Name' => $row['name'],
    'Total' => $row['total']    );
};
echo($combinedResults['code'][0]['Total']);
?>

and script return Undefined index: code in echo row

1
  • 1
    result of print_r($combinedResults) and $row ? Commented Dec 8, 2014 at 11:01

2 Answers 2

1

Typo:

Change

$combinedResults[$row['code']][] = array( 

to

$combinedResults['code'][$row['code']] = array( 
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think its a typo.
Working now but return only one column name: print_r($combinedResults['code'][0]'Total']); return 135 but print_r($combinedResults['code'][0]['Name']['Total']); return only one letter of record
@Klapsius When you are developing, please set display_errors to on and error_reporting to E_ALL (or -1). You will have noticed that the index does not exist. PHP will issue warnings and notices. It will also treat ['Total]` as [0] and only display the first character of $combinedResults['code'][0]['Name']. You need to do: print_r($combinedResults['code'][0]['Total']); to see the Total
0

Here your "code" index must be value from the database. That's why there is no such index in associative array. Or, if you need "code" index, you need to rewrite like this (if I've understood correctly):

while ($row = $sql -> fetch(PDO::FETCH_ASSOC)) {
   $combinedResults['code'][] = array( 
   'Name' => $row['name'],
   'Total' => $row['total']    );
};

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.