• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 127
  • Last Modified:

Getting from database to make one row

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
0
Jasmine Ikhreishi
Asked:
Jasmine Ikhreishi
  • 6
  • 5
  • 5
  • +1
2 Solutions
 
Ray PaseurCommented:
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
0
 
Julian HansenCommented:
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

0
 
Julian HansenCommented:
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

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Jasmine IkhreishiAuthor Commented:
Im using PostgreSQL  is it the same?
0
 
Ray PaseurCommented:
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

0
 
Jasmine IkhreishiAuthor 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?
0
 
Ray PaseurCommented:
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?
0
 
Jasmine IkhreishiAuthor Commented:
My database is on PostgrelSQL thats why
0
 
Ray PaseurCommented:
0
 
Jasmine IkhreishiAuthor 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.
0
 
Julian HansenCommented:
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

0
 
Julian HansenCommented:
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

0
 
Ray PaseurCommented:
... but I dont know how to put each in a column and add the other variables to it.
Please see lines 151, et seq, in the code snippet posted here:
https://www.experts-exchange.com/questions/28969738/Getting-from-database-to-make-one-row.html#a41797963
0
 
Brian TaoSenior Business Solutions ConsultantCommented:
Another suggestion is to use PostgreSQL built-in ARRAY_AGG() function.  It's very similar to GROUP_CONCAT() in MySQL.
0
 
Julian HansenCommented:
$query= "SELECT * from vouchers WHERE parsing_date=CURRENT_DATE ";

Open in new window

Indicates we might be dealing with more than one contact_id in the results. Therefore any solution is going to have to take into account a result set that requires grouping on the contact_id.
In light of this, Brian's comment above is one that should probably be taken the most seriously as it lets the DB do the most work.
A MySQL implementation would be simple
$query =  <<< QUERY
  SELECT 
    `contact_id`, 
    COUNT(*) AS `rows`, 
    CONCAT(GROUP_CONCAT(`insurance`), ' rows') AS `insurance`
  FROM `vouchers`
  WHERE `parsing_date`=CURRENT_DATE
  GROUP BY `contact_id`
QUERY;
$result = $conn->query($query);
echo "<table>";
while($row = $result->fetch_object()) {
  echo <<< ROW
    <tr>
      <td>{$row->contact_idk}</td>
      <td>{$row->rows}</td>
      <td>{$row->insurance}</td>
    </tr>
ROW;
}
echo "</table>";

Open in new window

A PostGres version of this might be
$query =  <<< QUERY
SELECT 
  contact_id, 
  concat(count(*), ' rows') AS rows, 
  array_agg(insurance) AS insurance 
FROM vouchers 
GROUP BY contact_id
QUERY;

$result = pg_query($conn,$query);
echo "<table>";
while($row = pg_fetch_object($result)) { 
  echo <<< ROW
    <tr>
      <td>{$row->contact_idk}</td>
      <td>{$row->rows}</td>
      <td>{$row->insurance}</td>
    </tr>
ROW;
}
echo "</table>";

Open in new window

You can see the query in this SQLFiddle
0
 
Jasmine IkhreishiAuthor 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
0
 
Julian HansenCommented:
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

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 6
  • 5
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now