Linking two PHP objects together - php

I have these two objects:
$userinfo->pilotid;
$departures->total;
I'm trying to get $departures->total for specific pilotid in $userinfo = $userinfo->pilotid.
However, I'm not sure how can I link them so it echoes A for B. I have something like this but it does not display anything.
<?php echo $pilotid->$departures->total; ?>
Additionally, the first object is called like this:
$pilotid = Auth::$userinfo->pilotid;
This is the structure of the table where the objects are gathered from, using a query.

Stemming from the data provided by the OP, I am assuming, that $departures has a 1:n relationship with $userinfo, $userinfo being the 1 containing the pilotid.
So, in oder to find out how many departures that pilot had in total, there's two possible ways, one by using a subquery, which would mean something like this:
SELECT (SELECT COUNT(*) FROM `departures` WHERE `pilot_id` = ID) as total, * FROM pilots;
In this case, your total would be in the total column of your $userinfo query.
The second attempt makes use of actual PHP. In this scenario, you do the counting yourself.
First step: Getting the pilot information:
$userinfo = array();
while($row = fetch()) {
$row->total = 0;
$row->departures = array();
$userinfo[$row->pilotid] = $row;
}
These lines will give you the pilot data keyed to their IDs in an array.
Step two. Glueing the departures to the pilots.
while($row = fetch()) {
if(isset($userinfo[$row->pilotid])) {
$userinfo[$row->pilotid]->departures[] = $row;
++$userinfo[$row->pilotid]->total;
}
}
If this isn't what you're looking for, I will be needing more information from you, however like this you will be able to get the departures of the pilots either by making use of the total variable in the $userinfo object, or by simply calling count on the departures array.
Another variant, which keeps the actual departures and the pilots apart would look like this:
First step: Getting the pilot information:
$userinfo = array();
while($row = fetch()) {
$row->total = 0;
$userinfo[$row->pilotid] = $row;
}
These lines will give you the pilot data keyed to their IDs in an array.
Step two. Glueing the departures to the pilots.
$departures = array();
while($row = fetch()) {
if(isset($userinfo[$row->pilotid])) {
$departures[] = $row;
++$userinfo[$row->pilotid]->total;
}
}
I hope you will find these suggestions useful.
Edit:
After a few additional information from the OP, I suggest changing the query used to access the information in question.
This is the original code by the OP
$dep_query = "SELECT COUNT(pilotid) as total, depicao, pilotid FROM phpvms_pireps GROUP
BY depicao, pilotid ORDER BY total DESC LIMIT 5";
$fav_deps = DB::get_results($dep_query);
foreach($fav_deps as $departure)
{
$dep_airport = OperationsData::getAirportinfo($departure->depicao);
$pilotid = Auth::$userinfo->pilotid;
?>
<tr class="awards_table1">
<td width="10%"><?php echo $departure->depicao; ?></td>
<td width="10%"><img src="<?php echo Countries::getCountryImage($dep_airport->country); ?>" /></td>
<td width="60%"><?php echo $dep_airport->name; ?></td>
<td width="20%"><?php echo $pilotid->{$departures->total}; ?></td>
</tr>
<?php
}
?>
First thing we'll change is the query used to get the departures. Why fetch all the information, if we actually only want the one of the pilot in question?
$pilotid = $userinfo->pilotid; //As per Chat discussion
$dep_query = "SELECT COUNT(depicao) as total, depicao FROM phpvms_pireps WHERE pilotid = $pilotid GROUP BY depicao ORDER BY total DESC LIMIT 5";
This query will return the Top 5 of the departures from the different airports, which have been run by the pilot in question. As for the rest:
$fav_deps = DB::get_results($dep_query);
if(is_array($fav_deps)) { //For the general use
foreach($fav_deps as $departure) {
$dep_airport = OperationsData::getAirportinfo($departure->depicao); ?>
<tr class="awards_table1">
<td width="10%"><?php echo $departure->depicao; ?></td>
<td width="10%"><img src="<?php echo Countries::getCountryImage($dep_airport->country); ?>" /></td>
<td width="60%"><?php echo $dep_airport->name; ?></td>
<td width="20%"><?php echo $departure->total; ?></td> //Here is the actually changed Layout code
</tr>
<?php
}
} else echo "This pilot didn't have any departures yet.";
?>
With these alterations, your code should output the desired result. It is completely untested though. However it should give you the right idea.

I think what you need is this (note the curly brackets):
<?php echo $pilotid->{$departures->total}; ?>
Unless I'm misunderstanding the question...

Related

Data cross matching with mysql two tables, value display in table using PHP mySql

I am having some trouble with php and mysql, I am even not sure how to properly ask the question, it seems very complex. Still if anyone can help me, i will be very thankful.
i have two tables
(allunit.sql)
id - unit_name
12 - MIS
14 - MIT
15 - ENG
when someone click enroll button from browser (unit_id) will store in enrollment table. if some one enroll into the unit, button will show (Already Enrolled), not not it will show "Enroll"
enrollment.sql
enroll_id - unit_id
1 - 12
2 - 14
I am using this query
$unit = SELECT * FROM allunit;
$enroll = SELECT * FROM enrollment;
$row_enroll = mysqli_fetch_assoc($enroll);
while($row = mysqli_fetch_assoc($unit)) {
if($row['id']==$row_enroll['unit_id']){
$button = 'Already enrolled';
}else{
$button = 'Enroll';
}
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['unit_name']; ?></td>
<td><?php echo $button; ?></td>
</tr>
<?php } ?>
if i add one unit button changes to "already Enrolled" for that unit, but if i add more than one, still only one button changes. other stays same "enroll".
I know my question is reallty messy, hope you will understand. Badly need help. Thank you
First, you have to tell the database to run your query, it is not enough to place a query in a text string. This is done, in this case using the query() method.
Second, as you want to process the Enrolments once for each of the Units, it would be useful to unload at least the Enrolment into an array so it is easily reusable
// assuming you have a connection and its in $con
$sql = 'SELECT * FROM allunit';
$units = $con->query($sql);
$sql = 'SELECT unit_id FROM enrollment';
$res2 = $con->query($sql);
// make an array of just the enrolment id's as that all you need
// so we can use in_array() later to do the test for are you already enrolled
$enrols = [];
while ($row = $res2->fetch_assoc()){
$enrols[] = $row['unit_id'];
}
while ($unit = $units->fetch_assoc() ) {
if ( in_array($unit['id'], $enrols) ) {
$button = 'Already enrolled';
}else{
$button = 'Enroll';
}
?>
<tr>
<td><?php echo $unit['id']; ?></td>
<td><?php echo $unit['unit_name']; ?></td>
<td><?php echo $button; ?></td>
</tr>
<?php
} // endwhile
?>
There are two problems I see in your code:
mysqli_fetch_assoc() is called on a MySQL result, not a query. You need to call mysqli_query() first. You can see an example in the docs: https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
When you get a result, such as $row_enroll, it's a collection of rows, so you can't use it with a column directly, i.e. $row_enroll['unit_id'] won't give you anything.
Finally, it doesn't appear that a comparison between two separate datasets like this is going to work well for you, at least with the current code. Consider using JOINs to return just one dataset.

Row within a row with JSON

I have a webpage where it shows the lists of Projects and the monitoring of its progress/finances for every quarter. As shown below:
As you can see, my table is comprises of Project Name and a lists of sub-title's underneath it. And a series of columns per each quarter. Thru PHP I was able to populate the list of sub-titles under the Project Name, which also being fetched from the server side. Here's the code:
$sql = mysqli_query($con," My SELECT Statement ");
$i=0;
while($row = mysqli_fetch_assoc($sql)){
$ptitle = $row['Title'];
$iname = $row['Item'];
if($i%1)
{
?>
<?php } else { ?>
<tr>
<?php } ?>
<td width="25%"><?php echo $ptitle; ?></td>
<td></td>
</tr>
<tr>
<td><?php echo "<ul style='list-style-type: none;'><li>".nl2br($iname)."</li></ul>"; ?></td>
<td contenteditable="true" name="v1"></td>
Note: ptitle = ProjectName and iname = Semi-title underneath the Project's name.
Now, as you can see, the Project Name column literally "conquer" a single row on the left. Yet, the rows under the column of each quarter, should have its own separately, and must be parallel to the every sub-title underneath the Project Name. (Please refer to the image above for this) the only problem am encountering is... how can I make an editable row from inside a row, without affecting mysqli result? coz basically my table right now is kinda look like this:
Anyone who's more experience on this? I need your help.
PS: ...and oh! You might be wondering why do I include JSON in the title? It is because, I originally use JSON for editing those table rows before I even use mysqli_fetch_array. But when I include the results of the array inside the <table> tag, everything's changed and JSON is no longer working. So as of now, I am force to do it manually, meaning typing each <td contenteditable=true> in all of those rows. Yet, its not the desired output since I need another row within an existing row. Ideas? Anyone?
Figure Two:
Figure Three:
Count the number of lines in $iname, and then use a loop to create that many rows of contenteditable cells. You can also use this in the rowspan attribute of the <td> containing the title and subtitles.
$rows = substr_count($iname, "\n") + 1;
for ($i = 0; $i < $rows; $i++) {
echo "<tr>";
if ($i == 0) { ?>
<td rowspan='<?php echo $rows;?>' width='25%'><?php echo $ptitle . "<br>" . nl2br($iname);?></td>
<?php }
?>
<td contenteditable="true" name="v1"></td><td contenteditable="true" name="v2"></td>...
</tr>
<?php }
DEMO

PHP How do you separate your results to echo in two divs of the one page?

I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!

mysqli php problems showing orders in groups / SELECT DISTINCT shows only one result

I'm having some trouble with my php / mysqli code, hopefully you can help me.
I'm currently working on an online shop for a school project. Customers are able to buy things, they get an order number and I'm writing their user_id, the order number, the different products and some other things in a relation.
now the administrator should be able to see all orders.
right now it looks like this (I copied my table into a word table, so it's easier to see the structure):
part of the table
So the problem is that I have two different order numbers (80425 and 14808) and I want to show each number (and the name and adress of the custumer, too) only one time, but for each order number all different ordered products.
I imagine it like this:
part of the table (more organised)
(it's german, I hope you still get what I mean)
So this is the code right now for getting all the information and show them in a table:
$selection = "SELECT * FROM kundenbestellungen, zahlart, produkte, user, status_bestellung, wohnsitz, kontodaten
WHERE b_zahlung_id = z_id
AND b_produkte_id = p_id
AND b_user_id = u_id
AND b_status_id = sb_id
AND w_user_id = u_id
AND d_user_id = u_id";
$sql = mysqli_query ($dblink, $selection) OR die (mysqli_error($dblink));
if (mysqli_num_rows ($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
?>
<tr>
<td>
<?php /*Change the status to sent*/
if ($row['b_status_id'] == '0') {
echo $row['sb_status'];
?>
<form action="admin-bestellungen.php" method="POST">
<input type="hidden" name="id" value="<?php echo $row['b_id']?>">
<input type="submit" name="versenden" value="versenden">
</form>
<?php
} else {
echo $row['sb_status'];
}
?>
</td>
<td> <?php echo $row['b_nummer'];?></td>
<td><?php echo $row['u_vorname']." ".$row['u_nachname'];?></td>
<td><?php echo $row['p_produktname'];?></td>
<td><?php echo $row['b_menge_produkt'];?></td>
<td><?php echo $row['b_einzelpreis'];?></td>
<td><?php echo $row['z_art'];?></td>
<td><?php echo $row['b_zeitpunkt'];?></td>
</tr>
<?php
}
}
I'm really confused. I tried this below the $selection part, just to start with something:
$anzahl_bestellungen = "SELECT COUNT(DISTINCT b_nummer) AS nr FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['nr']);
and the code counts the amount of the different order numbers (8). But if I use it without COUNT, it shows only the first order number (80425) and also counts only 1 result and doesn't get the other 7 numbers.
$anzahl_bestellungen = "SELECT DISTINCT b_nummer FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['b_nummer']);
$b = count($bestell['b_nummer']);
echo "<br>".$b;
I also tried to work something out with GROUP, but then the code shows only one item for each order number.
I tried to work with a for-loop as well, but that didn't work out either.
I thought about a multidimensional array, but I wasn't able to think through that whole thing, I'm not very good at php / mysqli.
So I have no idea how to go on. Maybe you can help me. This is my first question, so please let me know if I need to be more specific or you need more code or anything.
thanks a lot!

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