Creating a static table header - php

I know there are lots of plugins there to display a table with static headers. My issue is that i have a for loop which returns the values under this table:
foreach($ftsProducts as $x) {
$content .= "<tr class='highlight'>
<td class='reportCell' title='" . $x['BaseCode'] . "'>" . $x['Description'] . "</td>
<td class='reportCell'>" . $x['Fit'] . "</td>";
foreach($sizes as $y) {
$content .= "<td class='reportCell'>" . $x[$y] . "</td>";
}
$content .= "<td style='font-weight: bold; text-align: center;'>" . $x['Total'] . "</td>
</tr>";
}
$content .= "</table>";
Anyone got any suggestions or advice.
Many thanks

As far as i understand, your problem is not related to PHP, but to HTML and CSS. Static headers are tricky to achieve and there are probably browsers, which won't let you do them. Have a look at this solution, for example:
http://www.imaputz.com/cssStuff/bigFourVersion.html
By viewing the source of the page, it should -- imo -- be obvious how you have to build your table with PHP.
HTH

Related

Replacing the Null output of a MySQL query with a "String" in a php table

From the research i conducted in SO, this is the only other question similar to what i need, but im afraid that i didnt help me (How to replace null results in sql query result table with a string?).
I have a table that prints the Medical History of a Patient, and the table cells are restored from a database.
A portion of the code is down below:
echo "<tr>";
echo "<th>MRI Onset Localisation</th>";
echo "<th>CNS MRI Lesions Y/N </th>";
echo "<th>CNS MRI Lesions No.</th>";
echo "<th>CNS MRI Location</th>";
echo "<th>Person Signing the form</th>";
echo "<th>Documented at</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Onsetlocalisation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['smoker'] . '<br>' . $row['cigars'] . '<br>' . $row['cigardate'] . "</td>";
echo "<td>" . $row['onsetsymptoms'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRIonsetlocalisation'] . "</td>";
echo "<td>" . $row['MRIenhancing'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRInum'] . "</td>";
echo "<td>" . $row['MRIenhancinglocation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['signer'] . "</td>";
echo "<td>" . $row['reg_date'] . "</td>";
echo "</tr>";
And the MySQL Query that returns those fields is
$sql = "SELECT * FROM tblName WHERE somefield = $somevar";
The thing is... Some of those fields are allowed to have NULL as a value, but for the front end of the app, i want the table cells that contain NULL values to print a standard string such as "N/A" or "Empty" but i need it to be done inside of the php table portion of my code, or so i think...
I found numerous questions about replacing NULL with a string inside of the MySQL query, but i don't care about that since the query doesn't appear at the end user outside of the table.
I tried to implement the coalescing operator in the following way, but no nothing was displayed:
echo "<td class='tdclass exempt'>" . $row['MRInum'] ?? "N/A" . "</td>";
Any help is absolutely welcome.
You need to put the expression in brackets to make it clear which parts are supposed to be evaluated by the null coalescing operator:
echo "<td class='tdclass exempt'>" . ($row['MRInum'] ?? "N/A") . "</td>";
If you don't, it thinks the "<td class='tdclass exempt'>" is part of the text to be checked for existence - which means it always returns true because that hard-coded text always exists.
You can do this in two ways.
From SQL:
COALESCE(fieldName, 'N/A') AS fieldName
will replace NULLs with, you guessed it, 'N/A'.
Otherwise, when you fetch the row,
$row = $stmt->fetch(PDO::FETCH_OBJECT);
you can vet it:
$replacements = [
'MRI_Data' => 'N/A',
'MRI_Type' => [
'001' => 'Single Scan',
'002' => 'Multi Scan',
'003' => 'Pulsed',
'(null)' => 'N/A',
],
];
foreach ($row as $key => $value) {
if (array_key_exists($key, $replacements)) {
if (is_array($replacement[$key])) {
if (empty($value)) {
$value = '(null)';
}
if (array_key_exists($value, $replacement[$key])) {
$row[$key] = $replacement[$key][$value];
}
} else {
if (empty($value)) {
$row[$key] = $replacement[$key];
}
}
}
}

Get data from form using PHP

I have a php file that creates a table for me using data fetched from a mysql database.
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "<td>" . $row['District'] . "</td>";
echo "<td>" . $row['Population'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "<td><input type=\"number\" name="quantity" id="quantity"></td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
At the end of each row, I have an input number so that I can calculate the amount of each product(countries in this case). How could I get the amount of each country, multiply it by the price and return a total at the end of my table?
If you want to do it with PHP, you have to do it in two steps, because the PHP is processed in the server. So you would enter all the quantities you want and when you press the "Compute" button, the page would send all the values to the server who would compute everything you want and give you the final result.
A problem that I see with this solution is that once you have get all the quantities you want, you would have to get the prices once more. I don't its very efficient because you already have them on the first page. I see two solutions here :
When you display the values, keep track of the prices in a $_SESSION field, thus you will be able to access them after leaving the page, without having to get them from the database.
When you display the values, display the prices in an input field (I would recommend as readonly so that the user won't change this value here), and thus they would be included in the $_POST (or $_GET, if you use this) variable that your browser would send to the server.
If you're only interested to display the value, without using it after, you can use javascript to compute it, it might be easier.
Even though it's not the point here, you should be careful when displaying inputs via PHP on a while loop, because here all of your inputs have the same id, which would make thing harder to compute what you want to.
Hope it helps!
You must add a form tag around the table and then sum record price * qty on every row
What I did here is I checked if the quantity is set in the POST variable or not. if it exists I put data in quantity value. after that, you must make the name of quantity capable of taking array inside with the key of record Id.
after that, if the form submitted the quantity will send back to the page as a query string. then I multiply the price with quantity and add it to sum varaible. after finishing the loop and echo out the sum variable at the end of the table.
$html = '';
if ($result->num_rows > 0) {
$html .= '<form method="GET" action="" target="_self>';
$row = $result->fetch_assoc();
if(isset($_GET['quantity'][$row['ID']]))
$qty = $_GET['quantity'][$row['ID']];
else
$qty = 0;
$sum = 0;
// output data of each row
while ($row) {
$html .= '<tr>';
$html .= '<td>' . $row['ID'] . '</td>';
$html .= '<td>' . $row['Name'] . '</td>';
$html .= '<td>' . $row['CountryCode'] . '</td>';
$html .= '<td>' . $row['District'] . '</td>';
$html .= '<td>' . $row['Population'] . '</td>';
$html .= '<td>' . $row['Price'] . '</td>';
$html .= '<td>
<input type="number" name="quantity[' . $row['ID'] . ']" value="' . $qty . '">
</td>';
$html .= '<td>' . ($sum += $row['Price'] * $qty) . '</td>';
$html .= '</tr>';
}
$html .= '<input name="submitForm" value="submitForm">';
$html .= '</form>';
$html .= '<tr>';
$html .= '<td>Total = '.$sum.'</td>';
$html .= '</tr>';
} else {
$html .= "0 results";
}
$conn->close();
echo htmlspecialchars($html);
remember to use htmlspecialchars to echo out the result.

How to create a table from api data

I have been working on this for awhile and I am maybe making this more difficult than it is. Any shared knowledge would be very much appreciated.
My code calls data using an API, I was able to display it as a ordered list but I wanted to make it more presentable using a table format.
Ideally I the results to be displayed grouped by day.
Below is what I have created so far, but it is not outputting anything currently:
echo "<table>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>Number of Asteroids</th>";
echo "</tr>";
echo "<tr>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->close_approach_date . "</td>";
foreach ($data->near_earth_objects as $date => $count) {
echo"<td>" . sizeof($count) . "</td></tr>";
}
}
echo "<tr>";
echo "<th>Asteroid Name</th>";
echo "<th>Asteroid Size</th>";
echo "<th>Velocity</th>";
echo "<th>Passing Earth By</th>";
echo "</tr>";
echo "<tr>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "</td><td>". $close_approach->miss_distance->kilometers . " km</td></tr> ";
}
echo"</table>";
You should avoid echoing HTML code whenever possible. You can use PHP Short tags <?= and ?> to inject PHP into your HTML code. This line
echo "<td>" . $close_approach->close_approach_date . "</td>";
can then be changed to
<td><?=$close_approach->close_approach_date?></td>
Furthermore I don't see any PHP opening and closing tags (<?php and ?>) to start and end your PHP code (although this may just be lacking in your example)
You're only looping through your table data <td> tags not your table row <tr> tags. You have to include these in your loop to keep creating a new table rows for every item in your loop:
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<tr>";
Finally, PHP offers an alternative syntax for control structures. Check out the PHP documentation
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You can use this to improve your existing code:
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
And turn it into something like this
foreach ($data->near_earth_objects->$date as $near_earth_object): ?>
<td><?=$near_earth_object->name?> <a href='<?=$near_earth_object->nasa_jpl_url?>'><?=$near_earth_object->nasa_jpl_url?></td>
<td><?=$near_earth_object->estimated_diameter->meters->estimated_diameter_min?> metres</td>
<? endforeach; ?>
I recommend creating the table as you'd like to see it just with HTML and then using PHP to dynamically populate it. What may help is, rather than having PHP echo all of the HTML, just use PHP to populate the data (i.e., separate data from display). Just as an example taken from here:
<?php foreach ($things as $thing): ?>
<li><?php echo $thing; ?></li>
<?php endforeach; ?>

Putting data into array then show it in a table

So i have 0 experience with array's and putting them into a table. I tried google but there are no good results
Currently my script is this
<?php
$cats = explode("|", $_POST['cat_name']);
echo $cats[0]; // cat_id
?>
<?php
$url = 'http://services.runescape.com/m=itemdb_rs/api/catalogue/items.json?category='.$cats[0].'&alpha=a&page=1';
$result = file_get_contents($url);
$jsonArray = json_decode($result);
print_r($jsonArray);
?>
with this as a result:
1{"total":5,"items":[{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=4798","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=4798","id":4798,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
brutal","description":"Blunt adamantite
arrow...ouch","current":{"trend":"neutral","price":222},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=810","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=810","id":810,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
dart","description":"A deadly throwing dart with an adamant
tip.","current":{"trend":"neutral","price":11},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=829","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=829","id":829,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
javelin","description":"An adamant tipped
javelin.","current":{"trend":"neutral","price":64},"today":{"trend":"positive","price":"+1"}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=867","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=867","id":867,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
knife","description":"A finely balanced throwing
knife.","current":{"trend":"neutral","price":23},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=804","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=804","id":804,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
throwing axe","description":"A finely balanced throwing
axe.","current":{"trend":"neutral","price":180},"today":{"trend":"neutral","price":0}}]}
So my question is : How do i put this into a table?
Something like this should do it:
<?php
echo "<table>";
foreach($jsonArray["items"] as $item) {
echo "<tr>
<td>" . $item["id"] . "</td><td>
<td>" . htmlspecialchars($item["type"]) . "</td><td>
<td>" . htmlspecialchars($item["name"]) . "</td><td>
<td><img src='" . $item["icon"] . "'></td></tr>";
}
echo "</table>";
?>

Search server for image and display it

The user on my site can currently search a mysql db via PHP, and the results are displayed on the same page inside a DIV, thanks to ajax...
What I need now is to display an image that is associated with the mysql results...
Say the result has ID=250, then I want a piece of code to search in a folder for an image with the name 250.jpg on the server...
And then display this image in a table column using php script...
Here is my php script that displays the results as well as where I want the picture to appear...
Please help me...
$qry_result = mysql_query($query) or die(mysql_error());
}
// Build Result String
$display_table = "<table align='center'>";
// Insert a new row in the table for each result
while($row = mysql_fetch_array($qry_result)){
$display_table .= "<tr>";
$display_table .= "<td class='ad_container' colspan='4'></td>";
$display_table .= "</tr>";
$display_table .= "<tr>";
$display_table .= "<td width='110' rowspan='2'>----- IMAGE HERE -----</td>";
$display_table .= "<td width='377' height='15'>$row[headline]</td>";
$display_table .= "<td width='67' rowspan='2'>$row[insert_date]</td>";
$display_table .= "</tr>";
$display_table .= "<tr>";
$display_table .= "<td height='15'>$row[price]:-</td>";
$display_table .= "</tr>";
}
$display_table .= "</table>";
echo $display_table;
This solution checks to ensure the image actually exists prior to display:
// absolute path to image directory
$path = '/var/www/vhosts/path/to/dir';
// basepath image directory
$basepath = '/path/to/dir';
// assuming you store JPEGs
$image = $row['id'] . '.jpg';
// start column output
$display_table .= '<td width="110" rowspan="2">';
// make sure image exists
if (file_exists($path . $image)) {
$display_table .= '<img src="' . $basepath . $image . '" />';
}
// end column output
$display_table .= '</td>';
I think something like this would work:
$display_table .= "<td width='110' rowspan='2'><img src='/image/folder/" . $row["id"] . ".jpg'/></td>";

Categories