PHP mysqli fetch_row - iterate over multiple records - php

I have been messing with this for 3 days now, researching and experimenting: it's time to ask for some help.
I have a bit of code for a schedule display page that loops over a database table, once per appointment type. It gathers all appointments of that type for the week, and returns them in a row, like this:
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| Name | Year | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Purp |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| IST | NA | 9-4 | | | | | | | ABC |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| OT | NA | | 8-2 | 8-2 | 8-2 | 8-2 | | | DEF |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
My code works exactly as I want it to, with one fatal flaw. If there's more than one row for a "Name", I get this as my row:
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| Name | Year | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Purp |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| IST | NA | 9-4 | | | | | | | ABC |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+
| OT | NA | | 8-2 | 8-2 | 8-2 | 8-2 | | | DEF |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+-+-----+-+-+-+-+-+-----+
| MTG | | 1-2 | | | | | | | | | 1-2 | | | | | | GHI |
| | | | | | | | | | | | | | | | | | JKL |
+------+------+-----+-----+-----+-----+-----+-----+-----+------+-+-----+-+-+-+-+-+-----+
So instead of inserting into the appropriate <td>, it makes a whole new set of them. It's really frustrating because I'm sure it's something simple, but I can't see it... :(
Code:
$apptnamestop = array("IST", "OT", "MTG", "TR-CN", "EVENT", "EN", "REC", "TO");
$daysofweek = array("1", "2", "3", "4", "5", "6", "0");
foreach ( $apptnamestop as $name) {
print str_repeat($tab, 8) . "<tr>\n";
print str_repeat($tab, 9) . "<td class=\"td1s\">$name</td>\n";
print str_repeat($tab, 9) . "<td class=\"td1s\">N/A</td>\n";
$getdataquery = "SELECT appointmentName as name
, appointmentType as type, appointmentStartDateTime as sdt
, appointmentEndDateTime as edt, appointmentPurpose as purp
from tblAppointments
where appointmentStaffIDsToAttend like '%{$_SESSION['user_id']}%'
and appointmentName = '$name'
and (appointmentStartDateTime >= DATE_ADD(CURDATE(), INTERVAL (9 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY)
and appointmentEndDateTime < DATE_ADD(CURDATE(), INTERVAL (16 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY))
";
$getdataqueryresults = $mysqli->query($getdataquery)
or trigger_error("<p class=\"error\">We're very sorry, but an error has occurred when interacting with the CHAIRS database. Please try again and see if the error repeats. If it does, please get the following information in its entirety to your database adminapptrator so the CHAIRS developer can get the error resolved.<br />Error Message: " . $mysqli->error, E_USER_ERROR);
$datarowcnt = $getdataqueryresults->num_rows;
if ($datarowcnt > 0) {
while ($row = $getdataqueryresults->fetch_row()) {
$rows[] = $row;
}
foreach ($rows as $row) {
$title = $row[0];
$type = $row[1];
$sdt = $row[2];
$edt = $row[3];
$purp = $row[4];
$c=7;
if ($type == 1) {
$typew = "Mandatory";
} else {
$typew = "Elective";
}
$sparts = explode(" ", $sdt);
$eparts = explode(" ", $edt);
$tdiff = getTimeDiff($sparts[1], $eparts[1]);
foreach ($daysofweek as $day) {
if ($title == $name) {
if ($day == date('w', strtotime("$sparts[0]"))) {
if ($sparts[0] == $eparts[0]) {
print str_repeat($tab, 9) . "<td class=\"td1s\">$sparts[1] - $eparts[1]<br />($tdiff) - $typew</td>\n";
$c--;
} else {
$s = strtotime("$sparts[0]");
$e = strtotime("$eparts[0]");
for ($i=$s; $i<=$e; $i+=86400) {
print str_repeat($tab, 9) . "<td class=\"td1s\">$sparts[1] - $eparts[1]<br />($tdiff) - $typew</td>\n";
$c--;
}
}
}
if ( $c > 0) {
$c--;
print str_repeat($tab, 9) . "<td class=\"td1s\"></td>\n";
}
}
}
}
$rc++;
} else {
foreach ($daysofweek as $day) {
print str_repeat($tab, 9) . "<td class=\"td1s\"></td>\n";
}
}
print str_repeat($tab, 9) . "<td class=\"td1s\">$purp</td>\n";
$purp = "";
print "</tr>\n";
}

The new rows are started here:
foreach ( $apptnamestop as $name) {
print str_repeat($tab, 8) . "<tr>\n";
print str_repeat($tab, 9) . "<td class=\"td1s\">$name</td>\n";
As you can see, this new row is started once per element in $apptnamestop, rather than once per row from the database. The code doesn't care how many matching rows it finds in the table, it is only going to insert one new tr per name.
There are a couple of ways to improve this situation, depending on your needs.
If you need to always insert a row per name, regardless of whether there is a matching row in the database, keep lines 4, 5 and 6 the same as they are now. We will need to modify the inner loop (foreach ($rows as $row)) to output the new table rows for every loop beyond the first one:
$rowCounter = 0;
foreach ($rows as $row) {
if ($rowCounter > 0) {
print "</tr>\n"; // Close the previous table row
print str_repeat($tab, 8) . "<tr>\n";
print str_repeat($tab, 9) . "<td class=\"td1s\">$name</td>\n";
print str_repeat($tab, 9) . "<td class=\"td1s\">N/A</td>\n";
}
$rowCounter++;
// Remainder of the loop code goes here
...
}
If you prefer to skip creation of the table row when no matching database row is found, move the row creation statements into the inner loop entirely; this way it will run only if database rows are found.
As a final note, consider implementing a view templating system; by separating your logic code from your display code, you can easily modify either one without breaking the other. Your code becomes much simpler to read and modify in the future.

Related

Remove repeating data in a column

I am currently developing an ordering system where a customer can order many items. I also have an admin where he/she can see all the orders on that day. The Admin can view the name of the customer, the total payable, the products and the quantity of the product the customer have ordered.
I am currently seeing this results using my query.
Name | Payable | Product | Quantity
Test | 165 | keychain | 3
Test | 165 | Tumbler | 1
Miguel | 525 | Keychain | 3
Miguel | 525 | Magic Mug | 3
Dandel | 1010 | keychain | 3
Dandel | 1010 | T-shirt | 2
Dandel | 1010 | Keychain | 3
Dandel | 1010 | Mug | 5
This is my query.
$result = mysql_query("
SELECT reservation.firstname, reservation.lastname, reservation.payable, reservation.city, orders.product, orders.qty, reservation.date
FROM orders
INNER JOIN reservation
ON orders.confirmation = reservation.confirmation
WHERE reservation.date = CURDATE() && reservation.city = '24th Floor'
");
while($row = mysql_fetch_array($result))
{
echo '<tr>';
echo '<td style="border: 1px solid black;">'.$row['firstname'].'</td>';
echo '<td>'.$row['payable'].'</td>';
echo '<td>'.$row['product'].'</td>';
echo '<td>'.$row['qty'].'</td>';
echo '</tr>';
}
I want to get results like this. How can I do it?
Name | Payable | Product | Quantity
Test | 165 | keychain | 3
| | Tumbler | 1
Miguel | 525 | Keychain | 3
| | Magic Mug | 3
Dandel | 1010 | keychain | 3
| | T-shirt | 2
| | Keychain | 3
| | Mug | 5
You can maintain some state while iterating which keeps track of whether the current row is a new name/payable:
$last_name_seen = NULL;
while ($row = mysql_fetch_array($result)) {
$firstname = "";
$payable = "";
if ($last_name_seen === NULL || $row['firstname'] != $last_name_seen) {
$last_name_seen = $row['firstname'];
$firstname = $row['firstname'];
$payable = $row['payable'];
}
echo '<tr>';
echo '<td style="border: 1px solid black;">'.$firstname.'</td>';
echo '<td>'.$payable.'</td>';
echo '<td>'.$row['product'].'</td>';
echo '<td>'.$row['qty'].'</td>';
echo '</tr>';
}
Note that your MySQL query should have some ORDER BY clause, to generate the ordering you want, e.g.
ORDER BY Name, Product;
As the comments above also suggest, if you are using a deprecated PHP API, you should consider upgrading to something more modern. But, the logic used in the above loop would not change much with changing the MySQL API.
You have to set flag for name & payable column & use array_column(),array_unique() to get unique column values :
<?php
$result = array(array("Name"=>"Test","Payable"=>'165',"Product"=>"keychain","Quantity"=>3),array("Name"=>"Test","Payable"=>'165',"Product"=>"Tumbler","Quantity"=>1));
$name_arr = array_unique(array_column($result, 'Name'));
$payable_arr = array_unique(array_column($result, 'Payable'));
$name_flag = 0;
$pay_flag = 0;
echo "<table border='1'>";
for($i=0;$i<count($name_arr);$i++)
{
for($j=0;$j<count($payable_arr);$j++)
{
foreach($result as $list)
{
if($list['Name'] == $name_arr[$i] && $list['Payable'] == $payable_arr[$j])
{
if($name_flag==0 && $pay_flag==0)
{
echo "<tr>";
echo "<td>".$name_arr[$i]."</td>";
echo "<td>".$payable_arr[$j]."</td>";
echo "<td>".$list['Product']."</td>";
echo "<td>".$list['Quantity']."</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td> </td>";
echo "<td> </td>";
echo "<td>".$list['Product']."</td>";
echo "<td>".$list['Quantity']."</td>";
echo "<tr>";
}
$name_flag++;
$pay_flag++;
}
}
}
$name_flag=0;
$pay_flag=0;
}
echo "</table>";
?>

PHP: Troubles on indexing a nested for-loop

I am trying to print a 3-dimensional array into a table. But the indexes are kinda fked up. When I use the following (psuedo)code:
...
<<print headers and stuff>>
for ( $i = 0; $i < count( $array ); i++) {
$itemArray = $array[i];
for ( $j = 0; $j < count( $itemArray; j++) {
$innerItem = $itemArray[j];
echo <<tr start + both indexes in td>>
foreach ($innerItem as $spec) {
echo <<td with item>>
}
echo <<tr stop>>
}
}
In this example I am using i as index for the outer array and j as an index for the inner array (pretty obvious).
The result I am getting from this is as follows:
| index i | index j | title1 | title2 |
| 0 | 0 | | |
| 1 | 0 | | |
| 2 | 0 | | |
| ... | ... | | |
Whilst I would expect:
| index i | index j | title1 | title2 |
| 0 | 0 | | |
| 0 | 1 | | |
| 1 | 0 | | |
| 1 | 1 | | |
| 1 | 2 | | |
| 2 | 0 | | |
| ... | ... | | |
The (original) full code is:
echo "<h1>Combat analysis</h1>";
echo '<table cellspacing="0" cellpadding="4" border="1"><tbody>';
echo "<tr><td>#Mon</td><td>#Att</td><td>DungLVL</td><td>CharLVL</td><td>Health</td><td>Weapon</td><td>No. potions</td></tr>";
for ($battleIndex = 0; $battleIndex < count($this->combatLog); $battleIndex++) {
$battle = $this->combatLog[$battleIndex];
for ($attackIndex = 0; $attackIndex < sizeof($battle); $attackIndex++) {
$attack = $battle[$attackIndex];
echo "<tr><td>" . $battleIndex . "</td><td>" . $attackIndex . "</td>";
foreach ($attack as $stat) {
echo "<td>" . $stat . "</td>";
}
echo "</tr>";
}
}
echo "</tbody></table>";
What is going wrong?
Tested your code and runs as expected. You should do a echo '<pre>'.print_r($this->combatLog).'</pre>'; and debug the array contents.
Also I would recommend you the following:
1) You can use foreach instead of for, example: foreach ($this->combatLog as $battleIndex => $battle)
2) If you're not sure that a array contains values you should first do a: if (is_array($this->combatLog) && count($this->combatLog) > 0)
3) For simplicity and code maintenance I would first loop the multi-dimensional array and turn it into a one dimension called $attacks containing a array per each attack indexed by keys that you can recognize, ej:
$attacks=array();
$attacks[]=array(
'Mon'=>$battleIndex,
'Att'=>$attackIndex,
'DungLVL'=>isset($stat[0])?$stat[0]:null,
'CharLVL'=>isset($stat[1])?$stat[1]:null,
'Health'=>isset($stat[2])?$stat[2]:null,
'Weapon'=>isset($stat[3])?$stat[3]:null,
'Potions'=>isset($stat[4])?$stat[4]:null,
);
Then you could define some columns for example:
$columns=array(
'Mon',
'Att',
'DungLVL',
'CharLVL',
'Health',
'Weapon',
'Potions',
);
Then print the table header like this:
echo '<tr>';
foreach ($columns as $column) {
echo '<td>'.$column.'</td>';
}
echo '</tr>';
And print rows like this:
foreach ($attacks as $attack) {
echo '<tr>';
foreach ($columns as $column) {
echo '<td>'.$attack[$column].'</td>';
}
echo '</tr>';
}

Coordinates from MySQL to HTML table (PHP, PDO, MySQL)

I am creating game which uses MySQL database to create "playing field".
In my MySQL table I have two columns pointX and pointY, both INT. I could also use POINT, but in my case these two columns are better solution.
| id | pointX | pointY | player | game |
|----|--------|--------|--------|------|
| 1 | -2 | 1 | 7 | 10 |
| 2 | -3 | 2 | 5 | 10 |
| 3 | 2 | -2 | 2 | 10 |
| 4 | -2 | -1 | 1 | 10 |
I should produce HTML table from this MySQL table. Something like this, but with no coordinateheaders (below those are only for easier understanding):
|-----|----|----|----|----|----|----|
| Y/X | -3 | -2 | -1 | 0 | 1 | 2 |
|-----|----|----|----|----|----|----|
| -2 | | | | | | 2 |
|-----|----|----|----|----|----|----|
| -1 | | 1 | | | | |
|-----|----|----|----|----|----|----|
| 0 | | | | | | |
|-----|----|----|----|----|----|----|
| 1 | | 7 | | | | |
|-----|----|----|----|----|----|----|
| 2 | 5 | | | | | |
|-----|----|----|----|----|----|----|
Plus.. every <td> should have attribute data-cell, which includes coordinates, as example data-cell="-2x-1".
What is the best way to get started?
$rng = $dbh->prepare('
SELECT MIN(pointX) AS minX, MIN(pointY) AS minY,
MAX(pointX) AS maxX, MAX(pointY) AS maxY
FROM field
WHERE game = ?
LOCK IN SHARE MODE
');
$qry = $dbh->prepare('
SELECT pointX, pointY, player
FROM field
WHERE game = ?
ORDER BY pointX, pointY
');
$dbh->beginTransaction();
$rng->execute([$game_id]);
$qry->execute([$game_id]);
$dbh->rollBack();
$limits = $rng->fetch();
$player = $qry->fetch();
echo '<table>';
for ($y = $limits['minY']; $y <= $limits['maxY']; $y++) {
echo '<tr>';
for ($x = $limits['minX']; $x <= $limits['maxX']; $x++) {
printf('<td data-cell="%dx%+dy">', $x, $y);
if ($player and $player['pointX'] == $x and $player['pointY'] == $y) {
echo htmlentities($player['player']);
$player = $qry->fetch();
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
It looks like you are already off to a good start. Assuming the number of cells for X and Y as $xcells and $ycells, the next step I would take is to build your table like so:
echo "<table>";
for ($i = -3; $i < $ycells; i++) {
echo "<tr>";
for ($j = -3; $j < $xcells; j++) {
echo "<td data-cell='" . $i . "y" . $j . "x'>";
}
echo "</tr>";
}
echo "</table>";

PHP display images from column value

Table
+-----+--------+---------+
| ID | Name | Images |
+-----+--------+---------+
| 001 | John | 5 |
| 002 | Mark | 3 |
+-----+--------+---------+
i would like to display like this
Jon, 001-1.jpg | 001-2.jpg | 001-2.jpg | 001-3.jpg | 001-4.jpg | 001-5.jpg |
Mark, 002-1.jpg | 002-2.jpg | 002-2.jpg | 002-3.jpg |
the images value on database table will be the number of images return to create images link
You can use this though. Didn't know why you found it difficult.
$c = 0
while (false !== ($data = fetch_array_as_row_function()))
{
echo "<tr>";
echo "<td>", $data["name"], "</td>";
for ($i = 0; $i < $data["images"]; $i++)
echo "<td>00", $c,"-", $i, "</td>";
echo "</tr>";
}
Here, the function fetch_array_as_row_function() is something equivalent to what mysql_fetch_array() does.

Print results of a SELECT query as preformatted text in PHP?

I'm looking for an easy and quick way to print out the results of a MySQL SELECT query in PHP as preformatted text. What I would like is to be able to pass a query object to a function and get a printout of the recordset like the command line MySQL client does when running SELECT statements.
Here is an example of how I want it to look (i.e. ASCII):
+----+-------------+
| id | countryCode |
+----+-------------+
| 1 | ES |
| 2 | AN |
| 3 | AF |
| 4 | AX |
| 5 | AL |
| 6 | DZ |
| 7 | AS |
| 8 | AD |
| 9 | AO |
| 10 | AI |
+----+-------------+
It's basically for a generic import script, I am doing a SELECT query and want to display the results to the user for confirmation.
sprintf is your friend, if you must have a non-HTML fixed width output.
ETA:
//id: integer, max width 10
//code: string max width 2
$divider=sprintf("+%-10s+%-13s+",'-','-');
$lines[]=$divider;
$lines[]=sprintf("|%10s|%13s|",'id','countryCode'); //header
$lines[]=$divider;
while($line=$records->fetch_assoc()) {
//store the formatted output
$lines[]=sprintf("| %10u | %2.2s |", $line['id'],$line['code']);
}
$table=implode("\n",$lines);
echo $table;
If you want to print out immediately instead of storing the results, use printf instead- same syntax. There is a reasonable PHP (s)printf tutorial here.
function formatResults($cols, $rows) {
echo'<table>';
echo '<tr>';
foreach ($cols as $v) {
echo '<th>' . $v['field'] . '</th>';
}
echo '</tr>';
foreach ($rows as $sRow) {
echo '<tr>';
foreach ($sRow as $v) {
echo "<td>$v</td>";
}
echo '</tr>';
}
echo '</table>';
}
$qry = $pdo->query('DESCRIBE table');
$cols = $qry->fetchAll(PDO::FETCH_ASSOC);
$pdo->query('SELECT * FROM table');
$rows = $qry->fetchAll(PDO::FETCH_ASSOC);
formatResults($cols, $rows);
Untested but should work.
Edit: Missed ['field'] index ;)

Categories