How do output combined results from two MySQL tables using PDO - php

I have the following two table structures in MySQL, which record details of a conference call and those participants that joined it:
Table: conference:
conference_sid, date_created, date_completed, RecordURL, PIN
*date_created and *date_completed are timestamps
Table: participants:
conference_sid, call_sid, call_from, name_recording
I want to output a simple table, that displays the following results for each conference_sid as a separate row:
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<tr id="conference_sid">
<td>date_created</td>
<td>duration: [date_completed - date_created in h/mm/ss]</td>
<td>
<li>call_from [for all participants in that conference_sid]
<li>call_from...
</td>
<td>
Call recording
</td>
</tr>
<tr id="conference_sid">
...
</tr>
</tbody>
</table>
I only want this table to show relevant results for conferences that have the same PIN as the user's Session::get('PIN')

You can combine the participants using GROUP_CONCAT
SELECT
conf.conference_sid,
date_created,
TIMEDIFF(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = 123
GROUP BY conf.conference_sid
Refer SQLFIDDLE and MySQL documentation about TIMEDIFF.
Now the application logic will be
<?php
$pin = 123;
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare(
'SELECT
conf.conference_sid,
date_created,
timediff(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = :pin
GROUP BY conf.conference_sid');
$stmt->bindParam(':pin', $pin);
?>
<table border="1">
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$stmt->execute();
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['date_created']; ?></td>
<td><?php echo $row['duration']; ?></td>
<td>
<table border="1">
<thead>
<th>call_sid</th>
<th>call_from</th>
<th>name_recording</th>
</thead>
<tbody>
<?php
$length = count(explode(',', $row['pid']));
$call_sid = explode(',', $row['call_sid']);
$call_from = explode(',', $row['call_from']);
$name_recording = explode(',', $row['name_recording']);
for ($i=0; $i < $length; $i++) {
?>
<tr>
<td> <?php echo $call_sid[$i]; ?> </td>
<td> <?php echo $call_from[$i]; ?></td>
<td> <?php echo $name_recording[$i]; ?> </td>
<tr>
<?php
}
?>
</tbody>
</table>
</td>
<td>
<a href="<?php echo $row['RecordURL']; ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
You will get the result set with comma(,) separated values in pid, call_sid, call_from, and name_recording. You can convert this string to array using explode.
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.

I won't do the PHP part, as I am not that knowledgeable in PHP, but here is the SQL:
SELECT *
FROM `conference`, `participants`
WHERE `conference`.PIN = $PIN AND
`participants`.conference_sid = `conference`.conference_sid
This will return rows with the information from conference and the participants of those conferences, joined into one row.

The following query will give you the information you need to display:
SELECT c.conference_sid
, c.date_created
, timediff(c.date_completed, c.date_created) AS duration
, p.call_from
, p.name_recording
, c.RecordURL
FROM conference c
JOIN participants p
ON c.conference_sid = p.conference_sid
WHERE c.PIN = :PIN
ORDER BY c.conference_sid
You will need to process the results with a nested loop. The outer loop should advance each time the conference_sid changes. The inner loop will display each element of the participants list for that conference.

This will be my take on it, it uses 2 separate queries to keep the data kinda separated. I use fetchAll() for brevity but this could have performance issues, luckily this can be accomodated. I didn't put any error checking, if you want it or you have questions, please ask
<?php
// assume $db is a PDO connection to the database
/* #var $db PDO */
$q = 'SELECT conference_sid, date_created, date_completed, RecordURL, PIN'
.' FROM conference';
// we need these
$conferences = $db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass');
// let's group them as CSV, and concatenate the contents with ":"
$q = 'SELECT conference_sid,GROUP_CONCAT(CONCAT_WS(":",call_from,name_recording)) AS parts '
.' FROM participants GROUP BY conference_sid';
$conf_parts = array();
foreach ($db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass') as $parts) {
// save the participants as an array, their data is still joined though
$conf_parts[$parts->conference_sid] = explode(',',$parts->parts);
// their contents will be exploded later
}
?>
<table>
<thead><th>Date</th><th>Duration</th><th>Participants</th><th>Recording</th></thead>
<tbody><?php foreach ($conferences as $conference) {
$csid = $conference->conference_sid;
// http://stackoverflow.com/questions/3108591/calculate-number-of-hours-between-2-dates-in-php
// Create two new DateTime-objects...
$date1 = new DateTime($conference->date_completed);
$date2 = new DateTime($conference->date_created);
// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);
?><tr id="<?php echo $csid; ?>">
<td><?php echo $conference->date_created; ?></td>
<td><?php echo $diff->format('H/i/s'); ?></td>
<td>
<ul><?php foreach ($conf_parts[$csid] as $participant) {
// we have each participant for this conference call
list ($call_from, $name_recording) = explode($participant,':');
// and now we have the required data from each participant
?><li><?php echo $call_from; ?></li><?php
} ?></ul>
</td>
<td>
Call recording
</td>
</tr><?php
} ?></tbody>
</table>

In this particular contex I prefer to use two separated queries. Here's how I would do it:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Could not connect to db';
exit;
}
$stmt_conferences = $db->prepare(
'SELECT
date_created,
timediff(date_completed, date_created) AS duration,
RecordURL,
conference_sid
FROM
conference
WHERE
PIN=:pin');
$stmt_conferences->bindParam(':pin', $pin);
$stmt_participants = $db->prepare(
'SELECT
name_recording,
call_from
FROM
participants
WHERE
conference_sid=:confsid');
$stmt_participants->bindParam(':confsid', $confsid);
?>
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$pin = 1; /* get your PIN here */
$stmt_conferences->execute();
while ($row = $stmt_conferences->fetch()) {
?>
<tr>
<td><?php echo htmlspecialchars($row['date_created'], ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($row['duration'], ENT_QUOTES); ?></td>
<td>
<?php
$confsid = $row['conference_sid'];
$stmt_participants->execute();
while ($participant = $stmt_participants->fetch()) {
?>
<li><a href="<?php echo htmlspecialchars($participant['name_recording'], ENT_QUOTES); ?>">
<?php echo htmlspecialchars($participant['call_from'], ENT_QUOTES); ?>
</a>
<?php
}
?>
</td>
<td>
<a href="<?php echo htmlspecialchars($row['RecordURL'], ENT_QUOTES); ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
Please notice that you have to add some code to handle errors and to correctly escape all data you echo (can you really trust your database?). Also element IDs should be unique within the entire document, you can have just one id="conference_sid" in your page. Use classes instead.
Edit
If you can really trust your database, then you can just output the contents of a field with code like this:
<?php echo $row['call_from']; ?>
but what happens if RecordURL contains for example the following string?
<script>alert("I am injecting some code....");</script>
It will happen that some unwanted code will be injected in your page, so it is always better yo use a safe function like htmlspecialchars() every time you need to echo some output:
<?php echo htmlspecialchars($row['call_from'], ENT_QUOTES); ?>
this way, any unwanted code won't be harmful.
I also added a basic TRY/CATCH construct to handle errors.
Hope this helps!

First, we need to get our result.
$vPIN = $_SESSION['PIN']; // or however you get your user's pin from session
$vQuery = "SELECT * FROM conference AS a LEFT JOIN participants as B USING (conference_sid) WHERE a.PIN='$vPIN'";
$oResult = $oDB->execute($vQuery);
$aRows = $oResult->fetchAll(PDO::FETCH_ASSOC);
note the prefixes: $v if for a simple variable, $o represents a ressource (which I like to think of as an object), $a represents an array. It's just for my mental sanity.
so now, we have an array, probably very big, containing every single row in the conference table times every corresponding row in the participants. Sweet, now let's build an array with some meaning in it.
foreach($aRows as $aRow) // maybe a bit confusing but the 's' changes everything: all rows vs one row
{if (!isset($aConferences[$aRow['conference_sid']]['infos']))
{$aConferences[$aRow['conference_sid']]['infos']['date_created'] = $aRow['date_created'];
$aConferences[$aRow['conference_sid']]['infos']['date_completed'] = $aRow['date_completed'];
$aConferences[$aRow['conference_sid']]['infos']['record_url'] = $aRow['RecordURL'];
$aConferences[$aRow['conference_sid']]['infos']['pin'] = $aRow['PIN'];}
$aConferences[$aRow['conference_sid']]['participants'][] = $aRow['call_from'];}
so what happens here is that for each row, if the infos for corresponding conference_sid haven't been set, they will be, and then we create a list from 0 to x of each call_from for that conference. print_r of that array with dummy values:
[1627]['infos']['date_created'] = 2013-11-26
['date_completed'] = 2013-11-29
['record_url'] = 'http://whatever.com'
['PIN'] = 139856742
['participants'][0] = Bob
[1] = gertrude
[2] = Foo
[8542]['infos']['date_created'] = 2013-12-01
['date_completed'] = 2013-12-02
['record_url'] = 'http://whateverelse.com'
['PIN'] = 584217
['participants'][0] = Family Guy
[1] = aragorn
[2] = obama
[3] = Loki
so here is a nice array with which we can build a html table! let's do that
$vHTML = '<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>';
foreach ($aConferences as $conference_sid => $aConference) // notice the s and no s again
{$vHTML.= '<tr id="' . $conference_sid . '">';
$vDateCreated = $aConference['infos']['date_created'];
$vDateCompleted = $aConference['infos']['date_completed'];
$vHTML.= '<td>' . $vDateCreated . '</td>';
$vHTML.= '<td>' . date('Y-m-d',(strtotime($vDateCompleted) - strtotime($vDateCreated))) . '</td>'; // you might have to debug that date diff for yourself.
$vHTML.= '<td><ul>'; // here a foreach for the participants
foreach ($aConference['participants'] as $call_from)
{$vHTML.= '<li>' . $call_from . '</li>';}
$vHTML.= '</ul></td>';
$vHTML.= '<td>' . $aConference['infos']['record_url'] . '</td>';
$vHTML.= '</tr>';}
$vHTML.= '</tbody></table>';
so here: for each conference create a table row with the infos, then for each participant, add a list item within the list. comment if you wish for any precision.
oh, and don't forget to do something with $vHTML. like echo $vHTML :)

Related

Making an array out of substr_replace

Hi everyone newbie here,
I'm taking on the tedious task of changing a bunch of IDs for a game and turning them into a string. As you can see here I do this for ID 29 and turn it into Sharpshooter. Is there a more efficient way for me to do this? Or am i stuck writing about 100 more if cases?
if ($rows[1] == 29)
{
$rows[1] = substr_replace("29","Sharpshooter",0);
}
Below is my full code and I have added a few more examples of what I'm talking about.
<?php
/* Link DB */
include_once 'config.php';
/* Initialize Connection */
$conn=sqlsrv_connect($serverName, $conn_array);
if ($conn){
}else{
die;
}
/* Prepare Statement Preparation */
$sql = "
SELECT TOP 25 G.CharacterName, G.JobCode, D.PVPWin, D.PVPLose, G.PvPExp, D.PVPGiveUp
FROM PvPRanking as G
INNER JOIN PVPScores as D
ON G.CharacterID = D.CharacterID
ORDER BY RANK() OVER (ORDER BY TotalRank ASC )
";
/* Assign Parameter values. */
$param1 = 1;
$param2 = 2;
// Array requirement for prepare statement.
$procedure_params = array(
array(&$param1, SQLSRV_PARAM_OUT),
array(&$param2, SQLSRV_PARAM_OUT)
);
/* The ACTUAL Prepare Statement */
$stmt = sqlsrv_prepare( $conn, $sql, $procedure_params);
/*Execute*/
sqlsrv_execute($stmt);
/* Variables */
$autoincrement = 0;
echo
'
<tr>
<th>Rank</th>
<th>Name</th>
<th>Class</th>
<th>Wins</th>
<!-- <th>Losses</th>
<th>Experience</th>
<th>Quit</th> -->
</tr>';
// Rank # to increment itself. I.E 1,2,3,4,5,6 etc..
while ($rows=sqlsrv_fetch_array($stmt))
{
$autoincrement++;
{
if ($rows[1] == 29)
{
$rows[1] = substr_replace("29","Sharpshooter",0);
}
if ($rows[1] == 30)
{
$rows[1] = substr_replace("30","Knight",0);
}
if ($rows[1] == 29)
{
$rows[1] = substr_replace("31","Dragon Slayer",0);
}
}
// Echo will spit out the rows and the data.
echo
'
<tr id=io>
<td> '.$autoincrement.' </td>
<b> <td style = "color:#AFA;"> '.$rows[0].' </td> </b>
<td> '.$rows[1].' </td>
<td> '.$rows[2].' </td>
<!-- <td> '.$rows[3].' </td>
<td> '.$rows[4].' </td>
<td> '.$rows[5].' </td> -->
';
}
?>
</table>
Create your own translation array. If the value is not a key in the array, do not replace it.
$replacements = [
29 => 'Sharpshooter',
];
$rows[1] = $replacements[$rows[1]] ?? $rows[1];
Assuming you are using a loop, the translation array should be written before the loop.
Alternatively, this could all be executed in the sql with a CASE block.
Ultimately, I would advise you to avoid performing this operation on every call of your query. You should simply add these translations as a new column in PvPRanking (or where most appropriate) and add them to the result set. In other words, whatever table has the JobCode values listed as unique values -- that table should receive the new column.
If you DON'T have a table that contains these unique jobcodes, then you should make one and join that table to your existing query. This is the most professional and maintainable solution because when you need to update the list, you only need to update the table instead of potentially multuple files in your project.

PHP While loop inside another and first while doesn't return other values

I am a little bit confused about using while loop inside another. Everything is fine with the second loop but the first one only returns one value and it is the same.
$aukciono_laimetojai_while = mysql_query("SELECT id, user_id, date, win
FROM tb_auction_winners WHERE user_id = 206");
$aukciono_istorija_while = mysql_query("SELECT user_id, aukciono_id,
COALESCE(SUM(bid), 0) AS bid, date FROM tb_aukciono_istorija
WHERE user_id = 206 GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_istorija_while)) {
while ($r2 = mysql_fetch_assoc($aukciono_laimetojai_while)) { ?>
<tr>
<td><?php echo $r2['date']; ?></td>
<td><?php echo $r2['win'] - $r1['bid']; ?> Eur</td>
<td>0 Eur</td>
<td>Plačiau <?php echo $r2['win'] . ' - ' . $r1['bid']; ?></td>
</tr>
<?php } } ?>
$aukciono_laimetojai_while returns:
click here
$aukciono_istorija_while returns: click here
Using these 2 while loops, the table looks like this: (www.i.stack.imgur.com/Os8Rx.png) (can't use more than 2 links, sorry)
Something is wrong with the second number (0.14 should not be the same in every row, only the first one) and it should return 3 rows ($r1 = mysql_fetch_assoc($aukciono_istorija_while) has 3 rows in the database). I do not know what is wrong here, using one while loop, everything is just fine. Could someone help me, please?
I have found the solution. I should use only one query in the while loop. Instead of this block of code:
$aukciono_laimetojai_while = mysql_query("SELECT id, user_id, date, win
FROM tb_auction_winners WHERE user_id = 206");
$aukciono_istorija_while = mysql_query("SELECT user_id, aukciono_id,
COALESCE(SUM(bid), 0) AS bid, date FROM tb_aukciono_istorija
WHERE user_id = 206 GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_istorija_while)) {
while ($r2 = mysql_fetch_assoc($aukciono_laimetojai_while)) { ?>
<tr>
<td><?php echo $r2['date']; ?></td>
<td><?php echo $r2['win'] - $r1['bid']; ?> Eur</td>
<td>0 Eur</td>
<td>Plačiau <?php echo $r2['win'] . ' - ' . $r1['bid']; ?></td>
</tr>
<?php } } ?>
I should use this (1 query, 1 while loop):
$aukciono_laimetojai_ir_aukciono_istorija_while = mysql_query("
SELECT tai.aukciono_id tai_aukciono_id, taw.win taw_win, taw.date taw_date,
COALESCE(SUM(tai.bid), 0) tai_bid FROM tb_auction_winners taw
JOIN tb_aukciono_istorija tai ON taw.id = tai.aukciono_id
WHERE tai.user_id = $usid GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_laimetojai_ir_aukciono_istorija_while)) { ?>
<tr>
<td><?php echo $r1['taw_date']; ?></td>
<td><?php echo $r1['taw_win'] - $r1['tai_bid']; ?> Eur</td>
<td>0 Eur</td>
<td class="placiau" data-aukciono-id=
"<?php echo $r1['tai_aukciono_id']; ?>">Plačiau</td>
</tr>
<?php } ?>

Making a HTML table based on SQL data in PHP

I am trying to make a dynamic HTML table with PHP, populating it with data from MySQL database. So far I have tried the while loop, but the result ends up in displaying the same first row it gets multiple times.
<div class = "container">
<p>Registered companies:</p>
<table border = "1px" align = "left">
<tr>
<th>Username</th>
<th>Company name</th>
<th>Company value1</th>
<th>Company value2</th>
</tr>
<?php
$compRowIncrement = 0;
while ($compRowIncrement < $companyRowCount) {
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
<td><?php echo $companyRow['company_name']?></td>
<td><?php echo $companyRow['company_value1']?></td>
<td><?php echo $companyRow['company_value2']?></td>
</tr>
<?php
$compRowIncrement++;
}
?>
</table>
</div>
It should display 3 rows of data for example (SQL query returns 3 different values). But so far I have achieved to get 3 rows (like I need) with the same data (first value it gets from the database).
How do I do it so each table row is populated with different data, as it is in the database.
I'm just learning, so if you don't mind ignore the css values in table :).
EDIT1 (Added query)//
$getPlayerCompanies = $MySQLi_CON -> query("SELECT DISTINCT *
FROM companies
LEFT JOIN player ON companies.player_id = player.player_id
LEFT JOIN users ON users.user_id = player.user_id
WHERE users.user_id =".$_SESSION['userSession']);
$companyRow = $getPlayerCompanies -> fetch_array();
$companyRowCount = $getPlayerCompanies -> num_rows;
Following query currently returns 3 rows, like it should.
where did the $companyRow values get populated?
I belive your code should be more like this (or with mysqli commands)
<?php
while ($companyRow = $getPlayerCompanies -> fetch_array() )
{
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
...
</tr>
<?php
}
?>

Display array inside arrary loop

I am working on a project where in I have tables of Invoices, Quotations and many more.
Where I am stuck is here -
I am saving values of quotation in to a table as a n array. Eg :-
If two services are selected then it saves it in this way : Service1, service2
Similarly its quantity and charges are saved in d same way:
Sqty : 1,1
Scharge: 100,300
Now For Invoice, I get the quotation id and service name from POST
$qdetails = mysql_query("SELECT * FROM tbl_quotation WHERE id ='$qid';")
or die(mysql_error());
$qdet = mysql_fetch_array( $qdetails );
$pcharge = $qdet['pcharge'];
$scharge = $qdet['scharge'];
$pqty = $qdet['pqty'];
$sqty = $qdet['sqty'];
Then display the output in the following table -
tbl_service_info is my table which has all the details of the service
<?php
foreach ($_POST['service'] as $key => $value) {
$query=("select * from tbl_service_info WHERE sname = '$value'");
$result=mysql_query($query) or die ("Unable to Make the Query:" . mysql_error() );
while($row=mysql_fetch_array($result)){
$product = #$row["sname"];
$prid = #$row["id"];
$sdetails = #$row["details"];
?>
<tr class="item-row">
<td class="item-name"><div class="delete-wpr">
<textarea name="services[]"><?php echo $value ; ?></textarea></div></td>
<td class="description"><textarea><?php echo $sdetails; ?></textarea></td>
<td><textarea class="description"><?php echo $sunit; ?></textarea></td>
<?php }
$scharge1 = explode(",",$scharge);
foreach ($scharge1 as $keysc => $valuesc) { ?>
<td><textarea class="cost" name="scharge[]"> <?php
echo $valuesc;?> </textarea> </td> <?php } ?>
<?php
$sqty1 = explode(",",$sqty);
foreach ($sqty1 as $key2 => $value2) { ?>
<td><textarea class="qty" name="snos[]"><?php echo $value2;?></textarea></td>
<?php } ?>
<td><span class="price"></span></td>
</tr>
<?php } ?>
This is what i get.
http://oi61.tinypic.com/286v30j.jpg
The Unit Cost and Nos are not looping with the main loop.
Please help.
Also correct my question If I have written it the wrong way.
Thanks...
Following my comment, here is the workaround that should work in your case.
You can use a temporary value to echo the correct part of the exploded string ($charge)
$i = 0;
while($row=mysql_fetch_array($result)){
// Rest of your code
$scharge1 = explode(",",$scharge);
// Remove that foreach ($scharge1 as $keysc => $valuesc) { ?>
<td><textarea class="cost" name="scharge[]">
<?php echo $scharge1[$i];?>
</textarea></td>
// Rest of your code, also change the NOS part
// Before the very end of your while loop, increment $i
++$i;
}

Trying to return a record set using PHP & MySQL (inner join)

I am new to PHP/MySQL to please bear with me. I am trying to have PHP write a table which returns a list of records from a join table. The SQL statement works perfectly when I run the query but I do not know how to write the function properly.
SQL statement which works:
SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID"
My functions:
function get_shares_by_member($member_ID) {
global $db;
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = $db->query($query);
$share_result = $share_result->fetch();
return $share_result;
}
function get_shares() {
global $db;
$query = "SELECT * FROM shares";
$share = $db->query($query);
$shares_table = $share->fetch();
return $share;
}
My action:
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_shares';
}
if ($action == 'list_shares') {
if (!isset($member_ID)) {
$member_ID = 0;
}
$shares = get_shares_by_member($member_ID);
$share = get_shares();
}
Here is my table:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares_table as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $share['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I know this is a lot to ask but I've been struggling with this for the past 3 days. Any help will be much appreciated! If anyone needs help with AD/Exchange, I'd be happy to share my knowledge in that area!
Thanks!!
From what I can see on here, this will produce a blank table with however many rows are returned for a number of reasons:
None of the columns returned by the get_shares_by_member function are share_ID or asset_ID, so those columns won't be filled in.
You are referencing percent_owner from $shares which, assuming is an array as you are using it in a 'foreach' loop, will need an index to reference it, or it should otherwise be $share['percent_owner']
The percent_owner field will be put in the 'asset cost' column at present as there is no blank cell produced to move it to the '% ownership' column where it would seem logical to have it.
Based on what you have posted so far, the following should suit your needs:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $shares['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I would recommend changing either the $share variable in the foreach, or the $share which is being set by get_shares(). Personally speaking, I would change the latter from
$share = get_shares();
to something like:
$shares_table = get_shares();
as it is essentially containing all of the information from the shares table, assuming the database abstraction layer function fetch() returns all results.
There could also be an issue when you are doing:
$share = $db->query($query);
$share = $share->fetch();
Going from different database abstraction layers I have seen, I would expect fetch() to be done as (using your variables)
$share = $db->fetch();
If the fetch() is requiring a result to be passed into it, then I would expect the code to look similar to:
$share_result = $db->query($query);
$share = $db->fetch($share_result);
a few points:
are you sure your query does not return any errors? If there are
errors, that might cause fetch() to fail
what DB class are you using? I would suggest that you please check
that there is a fetch() function and what parameters does it accept? For example, the fetch() may be invoked like $share_result->fetch() or $db->fetch() or $db->fetch($share_result) etc.
I might be wrong but it seems that the fetch() might be always
returning the first row from the resultset. Perhaps you might need
to do fetch() in a loop for reading all results
You may as well try using the default PHP functions. Here is a code snippet that explains how you may rewrite your functions using PHP's default mysql() library:
mysql_connect('your host', 'your user', 'your password'); function get_shares_by_member($member_ID) {
$output = Array();
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets ON shares.asset_ID = assets.asset_ID)
INNER JOIN members ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = mysql_query($query);
while ($row = mysql_fetch_assoc($share_result)) {
$output[] = $row;
}
return $output;
}
function get_shares() {
$output = Array();
$query = "SELECT * FROM shares";
$share = mysql_query($query);
while ($row = mysql_fetch_assoc($share)) {
$output[] = $row;
}
return $output;
}
Hope the above helps. Please feel free to let me know if there is anything that is not clear.

Categories