We help IT Professionals succeed at work.

Getting from database to make one row

Jazzy 1012
Jazzy 1012 asked
on
251 Views
Last Modified: 2016-09-15
My report will contain the person's id, # of rows, insurance and todays date
In my database person number 22 may contain
22      UH
22       AA
22        EI
Therefore in my report I want it to view as
22        3 rows           UH, AA,EI
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
I would take the easy way out here.  

SELECT {column names} FROM my_table

Retrieve the rows into an array.  Count the rows with PHP.  Collapse the field you need into an array and reformat it with implode().  

I'll try to give you a code sample in a moment.

If you're new to PHP and want to find some learning resources, this article might help.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Adapt to your code
// Create our result array
$rollup = array();
$conn = new mysqli('localhost','user','password','databse');
// Error checking for DB connect
// Get the rows from the db
$query = "SELECT id, insurance FROM thetable";
$result = $conn->query($query);

// We got rows ...
if ($result) {
  // Loop through results
  while($row = $result->fetch_object()) { 
    // Is this the first time we have seen this ID - if so make an entry for it
    if (empty($rollup[$row->id])) {
      $rollup[$row->id] = array(
        'insurance' => $row->insurance, 
        'rows' => 1
      );
    }
    // Otherwise add to existing and bump row count
    else {
      $rollup[$row->id]['insurance'] .= ",{$row->insurance}";
      $rollup[$row->id]['rows']++;
    }
  }
}
// Dump the results
echo "<pre>" . print_r($rollup,true) . "</pre>";

Open in new window

Sample output
Array
(
    [22] => Array
        (
            [insurance] => UH,AA,EI,AC
            [rows] => 4
        )

    [12] => Array
        (
            [insurance] => AA,AA
            [rows] => 2
        )

    [14] => Array
        (
            [insurance] => EI,GH
            [rows] => 2
        )

    [23] => Array
        (
            [insurance] => AB
            [rows] => 1
        )

    [25] => Array
        (
            [insurance] => DC
            [rows] => 1
        )

    [11] => Array
        (
            [insurance] => AA,AT
            [rows] => 2
        )

)

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
To get the output you wanted
echo "<pre>" . print_r($rollup,true) . "</pre>";
echo "<pre>";
foreach($rollup as $k => $v) {
   $rows = $v['rows'] > 1 ? 'rows' : 'row';
    echo "{$k}  {$v['rows']} {$rows} {$v['insurance']}\n";
}
echo "</pre>";

Open in new window

Output
22  4 rows UH,AA,EI,AC
12  2 rows AA,AA
14  2 rows EI,GH
23  1 row AB
25  1 row DC
11  2 rows AA,AT

Open in new window

Author

Commented:
Im using PostgreSQL  is it the same?
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Please see https://iconoun.com/demo/temp_jasmine_8.php

A couple of cautionary notes.  The use of "id" to identify anything other than the auto_increment primary key is likely to be confusing.  I used it here because you used it in the question, but in "real life" you do not want to do that.  Change the column name.

Make a Google search for the exact phrase "Should I Normalize My Database" and read the very interesting comments on both sides of the issue.

This script is mostly setup.  Hopefully the comments will help!  The demonstration starts on line 125.
<?php // demo/temp_jasmine_8.php
/**
 * Demonstrate some of the basics of MySQLi
 *
 * References that must be understood to use PHP and MySQL(i):
 *
 * http://php.net/manual/en/mysqli.overview.php
 * http://php.net/manual/en/class.mysqli.php
 * http://php.net/manual/en/class.mysqli-stmt.php
 * http://php.net/manual/en/class.mysqli-result.php
 * http://php.net/manual/en/class.mysqli-warning.php
 * http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
 *
 * http://php.net/manual/en/mysqli.construct.php
 * http://php.net/manual/en/mysqli.real-escape-string.php
 * http://php.net/manual/en/mysqli.query.php
 * http://php.net/manual/en/mysqli.errno.php
 * http://php.net/manual/en/mysqli.error.php
 * http://php.net/manual/en/mysqli.insert-id.php
 *
 * http://php.net/manual/en/mysqli-result.num-rows.php
 * http://php.net/manual/en/mysqli-result.fetch-array.php <-- DO NOT USE THIS
 * http://php.net/manual/en/mysqli-result.fetch-object.php
 */
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';


// CREATE AN ARRAY OF INFORMATION TO USE FOR TEST DATA
$test_names_arrays = array
( array( "id" => "22" , "xx" => "UH" )
, array( "id" => "22" , "xx" => "AA" )
, array( "id" => "22" , "xx" => "EI" )
)
;


// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// ACTIVATE THIS TO SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
// var_dump($mysqli);


// CREATING A TABLE FOR OUR TEST DATA
$sql
=
"
CREATE TEMPORARY TABLE my_table
( my_key INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, id     VARCHAR(24) NOT NULL DEFAULT ''
, xx     VARCHAR(24) NOT NULL DEFAULT ''
)
"
;

// IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res = $mysqli->query($sql))
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}

// ACTIVATE THIS TO SHOW THE RESULTS OF THE QUERY
// var_dump($res);


// LOADING OUR DATA INTO THE TABLE
foreach ($test_names_arrays as $person)
{
    // ESCAPE THE DATA FOR SAFE USE IN A QUERY
    $safe_id  = $mysqli->real_escape_string($person['id']);
    $safe_xx  = $mysqli->real_escape_string($person['xx']);

    // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLES
    $sql = "INSERT INTO my_table ( id, xx ) VALUES ( '$safe_id', '$safe_xx' )";

    // RUN THE QUERY TO INSERT THE ROW
    $res = $mysqli->query($sql);

    // IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
    if (!$res)
    {
        $err
        = 'QUERY FAILURE:'
        . ' ERRNO: '
        . $mysqli->errno
        . ' ERROR: '
        . $mysqli->error
        . ' QUERY: '
        . $sql
        ;
        trigger_error($err, E_USER_ERROR);
    }
}


// HERE IS THE START OF THE DEMONSTRATION
$sql = "SELECT id, xx FROM my_table WHERE id='$safe_id' ";
$res = $mysqli->query($sql);

// IF mysqli_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESULT OBJECT IN $res
// NOW WE CAN USE OTHER MYSQLI::RESULT PROPERTIES AND METHODS


// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num     = $res->num_rows;
$num_fmt = number_format($num);

// RETRIEVE THE RESULTS SET
$collection = [];
while ($row = $res->fetch_object())
{
    // ROW BY ROW PROCESSING IS DONE HERE
    $collection[] = $row->xx;
}

// SHOW THE REPORT
$report
= PHP_EOL
. $safe_id
. ' '
. $num_fmt
. ' rows '
. implode(', ', $collection)
;

echo $report;

Open in new window

Outputs:
22 3 rows UH, AA, EI

Open in new window

Author

Commented:
I have this so far what can I add to get the output I need/?
<?php 
error_reporting(E_ALL);
ini_set('display_errors' ,1);
require "connection.php";


$query= "SELECT * from vouchers WHERE parsing_date=CURRENT_DATE ";
$result = pg_query($conn,$query);



?>
  <?php 
  	while($row = pg_fetch_array($result))
	{ 


  ?>
  
  <tbody>


     <td><?php echo $row['client_id']; ?></td>

     <td><?php echo $row['insurance']; ?></td> 
     <td><?php echo $row['parsing_date']; ?></td>
    
    
    </tr>
  <?php  }?>  </tbody>

Open in new window


This gives me 3 rows: client id, insurance and date , However I want to add the row and put each insurance with each other?
Most Valuable Expert 2011
Author of the Year 2014

Commented:
PostgreSQL
It's nice if you tell us those "details" when you post the question.  And you might want to use Request Attention and ask a moderator to add this to the PostGreSQL Zone.  It's also nice to post your test data, or your code set, if you have some code already.

Short answer - mostly this is the same as MySQL.  Longer answer - Why in the world would you choose PostGreSQL instead of the vastly more popular and mature MySQL database?

Author

Commented:
My database is on PostgrelSQL thats why
Most Valuable Expert 2011
Author of the Year 2014

Commented:

Author

Commented:
I know how to return number of rows but I dont know how to put each in a column and add the other variables to it.
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
The code I posted will work with a minor change to post_gres.
require "connection.php";
// Create our result array
$rollup = array();
// Get the rows from the db
$query= "SELECT * from vouchers WHERE parsing_date=CURRENT_DATE ";
$result = pg_query($conn,$query);

// We got rows ...
if ($result) {
  // Loop through results
  while($row = pg_fetch_object($result)) { 
    // Is this the first time we have seen this ID - if so make an entry for it
    if (empty($rollup[$row->id])) {
      $rollup[$row->id] = array('insurance' => $row->insurance, 'rows' => 1);
    }
    // Otherwise add to existing and bump row count
    else {
      $rollup[$row->id]['insurance'] .= ",{$row->insurance}";
      $rollup[$row->id]['rows']++;
    }
  }
}
// Dump the results
echo "<pre>" . print_r($rollup,true) . "</pre>";
echo "<pre>";
foreach($rollup as $k => $v) {
   $rows = $v['rows'] > 1 ? 'rows' : 'row';
    echo "{$k}  {$v['rows']} {$rows} {$v['insurance']}\n";
}
echo "</pre>";

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
If you want to output as a table then you can replace lines 25 to 30 with this
echo "<table>";
foreach($rollup as $k => $v) {
   $rows = $v['rows'] > 1 ? 'rows' : 'row';
    echo "<tr><td>{$k}</td><td>{$v['rows']} {$rows}</td><td>{$v['insurance']}</td></tr>";
}
echo "</table>";

Open in new window

Most Valuable Expert 2011
Author of the Year 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Brian TaoOwner
CERTIFIED EXPERT
Top Expert 2014

Commented:
Another suggestion is to use PostgreSQL built-in ARRAY_AGG() function.  It's very similar to GROUP_CONCAT() in MySQL.
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
@Julian Hansen I copied your exact code here:
<?php 
error_reporting(E_ALL);
ini_set('display_errors' ,1);
require "connection.php";
// Create our result array
$rollup = array();
$query= "SELECT * from vouchers WHERE parsing_date=CURRENT_DATE ";
$result = pg_query($conn,$query);











?>

<!DOCTYPE html>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href = "http://fonts.googleapis.com/css?family=Roboto:400">

<style>
.responstable {
  margin: 1em 0;
  width: 100%;
  overflow: hidden;
  background: #FFF;
  color: #024457;
  border-radius: 10px;
  border: 1px solid #167F92;
  word-wrap: break-word;
}
</style>

</head>

<body>
<div class="container-fluid">
        <div>
        
          <h1>Clients</h1>
   
          
        </div>
        
<table class="responstable" rules='all' style='border-collapse: collapse;'>
<thead>
	<tr>
		<th>Client id</th>
		<th>Insurance</th>
		<th>Parsing Date</th>
		<th>Number of rows</th>
	 
	</tr>
</thead>

  
  <tbody>
  <tr>
  <?php 

// We got rows ...
if ($result) {
	// Loop through results
	while($row = pg_fetch_object($result)) {
		// Is this the first time we have seen this ID - if so make an entry for it
		if (empty($rollup[$row->client_id])) {
			$rollup[$row->client_id] = array('insurance' => $row->insurance, 'rows' => 1);
		}
		// Otherwise add to existing and bump row count
		else {
			$rollup[$row->id]['insurance'] .= ",{$row->insurance}";
			$rollup[$row->id]['rows']++;
		}
	}
}
// Dump the results
echo "<pre>" . print_r($rollup,true) . "</pre>";
echo "<table>";
foreach($rollup as $k => $v) {
   $rows = $v['rows'] > 1 ? 'rows' : 'row';
    echo "<tr><td>{$k}</td><td>{$v['rows']} {$rows}</td><td>{$v['insurance']}</td></tr>";
}
echo "</table>";
  ?>

 
    
    
    </tr>
  </tbody>
</table>
 
</div>

</body>
</html>

Open in new window


I just got error 500 on the display page
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
You need to work the sample code into your own code - if you cut and paste without adapting you will have problems

For instance - you have your own <table> echoed from the script - when you pasted my code in you included the <table> I had in my sample.
You can see your sample working against a MySQL database here
However, I would prefer to use the code in my previous post based on Brian's earlier suggestion

<?php 
error_reporting(E_ALL);
ini_set('display_errors' ,1);
require "connection.php";
// Create our result array
$rollup = array();
$query= <<< QUERY
SELECT 
  client_id, 
  count(*) AS rows, 
  array_agg(insurance) AS insurance,
  parsing_date
FROM vouchers 
where parsing_date = CURRENT_DATE
GROUP BY client_id, parsing_date 
QUERY;
$result = pg_query($conn,$query);
echo $conn->error;
?>

<!DOCTYPE html>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href = "http://fonts.googleapis.com/css?family=Roboto:400">

<style>
.responstable {
  margin: 1em 0;
  width: 100%;
  overflow: hidden;
  background: #FFF;
  color: #024457;
  border-radius: 10px;
  border: 1px solid #167F92;
  word-wrap: break-word;
}
</style>
</head>
<body>
<div class="container-fluid">
  <div>
    <h1>Clients</h1>
  </div>
  <table class="responstable" rules='all' style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th>Client id</th>
        <th>Insurance</th>
        <th>Parsing Date</th>
        <th>Number of rows</th>
       
      </tr>
    </thead>
    <tbody>
    <tr>
<?php 
// We got rows ...
  // Loop through results
  while($row = pg_fetch_object($result)) {
    echo <<< ROW
      <tr>
        <td>{$row->client_id}</td>
        <td>{$row->insurance}</td>
        <td>{$row->parsing_date}</td>
        <td>{$row->rows}</td>
      </tr>
ROW;
  }
?>
      </tr>
    </tbody>
  </table>
</div>
</body>
</html>

Open in new window

Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.