At the moment I'm trying to understand the template view pattern using PHP.
I got a table that gets filled by a command (using command pattern). At the moment the array gets iterated and filled in a table using foreach. I want to split the program logic and the displaying of the table but I don't know where to declare the table and how to fill it.
I understood it generally. I'm able to display a single information.
Two questions:
How to implement it when I want to display a table from a database?
How to implement the content that should be displayed on all pages?
Unfortunately everything I found is about template engines that I don't want to use at the moment.
Here is the command combined with a table generator. I want to split that into a command that retrieves the data and a view that displays the table.
$domains = ConcreteDomainFactory::getAllDomains();
echo '<table class="domain-table">';
echo '<thead>';
echo '<tr>';
echo '<th>ID</th>';
echo '<th>Domain</th>';
echo '<th>Beschreibung</th>';
echo '<th>aktiviert</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
if((is_array($domains) ===true) && (count($domains) > 0)){
$line_number = 1;
foreach($domains as $domain){
echo '<tr>';
echo '<td>' . $domain->getPkDomainId() . '</td>';
echo '<td>' . $domain->getDomain() . '</td>';
echo '<td>' . $domain->getDescription() . '</td>';
echo '<td>';
if($domain->getActive()){
echo 'ja';
}
else{
echo 'nein';
}
echo '</td>';
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';`
Related
I have the following table created with a foreach loop.
**foreach($data2['wow_accounts']['0']['characters'] as $key => $item) {
echo '<tr>';
echo '<td>';
echo $item['name'];
echo '</td>';
echo '<td>';
echo $item['realm']['name'];
echo '</td>';
echo '<td>';
echo '<button class="btnSelect">Select</button>';
echo '</td>';
echo '</tr>';
}
echo '</table>';**
I want that the script checks inside of the table "y4qt2_jsn_users" of the mysql database and under a certain id number, if the "params" entry is "ja". If this is true then this certain table row should get another tr class.
My idea is something like that, but how can i combine this with my foreach table loop?
$result = mysqli_query("SELECT params FROM xxx_users WHERE params = 'ja' AND id= '$id'");
if(mysqli_num_rows($result) == 0) {
// row not found, just loop without a certain <tr class=""
} else {
// row found, give this row a <tr class=""
}
Here is a screenshot of what I want. If the mysql condition "params=ja" is true the whole row should get a new tr styleclass, not just a cell.
Screenshot
Screenshot-Database
Assuming I understand correctly, this should work. Please sanitize database queries (especially if there is user input at any point). But as mentioned in the comments, I don't know where $id is set, and actually presume it's a value in the $item array, so maybe replaced with $item['Id']
foreach($data2['wow_accounts']['0']['characters'] as $key => $item) {
$result = mysql_query("SELECT params FROM y4qt2_jsn_users WHERE params = 'ja' AND
id= '$id'");
if(mysql_num_rows($result) == 0) {
$class_string = '';
} else {
$class_string = ' class="my-additional-class"';
}
echo '<tr'.$class_string.'>';
echo '<td>';
echo $item['name'];
echo '</td>';
echo '<td>';
echo $item['realm']['name'];
echo '</td>';
echo '<td>';
echo '<button class="btnSelect">Select</button>';
echo '</td>';
echo '</tr>';
}
There are a lot of ways to clean this up, and if you wanted fewer lines of code you can replace the entire if else block and the $class_string variable by using ternary operators inline. The goal was to make it easy for you to read and simple to understand. (I also prefer very verbose code myself)
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.
i have the following php code:
// Add the unsubscribers to an array
$unsubs = array();
foreach($unsubscribers->response->Results as $entry2) {
$unsubs[] = $entry2->EmailAddress;
}
// Loop through the subscribers
foreach($result->response->Results as $entry) {
echo '<tr class="'. $entry->EmailAddress.'">';
echo '<td>'. $entry->EmailAddress.'</td>';
echo '<td></td><td>';
// If the subscriber is in our unsubscriber array, output the email again
if(in_array($entry->EmailAddress, $unsubs)) {
echo $entry->EmailAddress;
}
echo '</td><td></td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}
Where the empty <td></td> are located i would like to place the following:
$getlists = new CS_REST_Campaigns($_POST['campaign_id'], $auth);
$getlistsresult = $wrap->get_lists_and_segments();
foreach($getlistsresult->response->Lists as $list) {
//echo $list->ListID;
}
$wrapcount = new CS_REST_Subscribers($list->ListID, $auth);
$resultcount = $wrapcount->get_history($entry->EmailAddress);
foreach($resultcount->response as $entrycount) {
$counts = array();
foreach($entrycount->Actions as $actions) {
if(!isset($counts[$actions->Event])) {
$counts[$actions->Event] = 0;
}
++$counts[$actions->Event];
}
echo '<td>';
if ($counts['Click']){echo $counts['Click'];}
echo '</td>';
echo '<td>';
if ($counts['Bounce']){echo 'Yes';}
echo '</td>';
echo '<td>';
if ($counts['Open']){echo $counts['Open'];}
echo '</td>';
}
This works to a degree, but the load time of the page is dramatically increased. I think to be honest my code will need tidying up. Any suggestions on how to speed this up?
There's not much I can see that is blatantly unoptimized in your code, there are functions calls that I don't know about, from your CS_REST classes, but we don't know what these functions do or if they can be slow or optimized.
With this information, the only thing I can see that might help you is using the SplFixedArray class. This will be notably useful if you have a lot of entries in your arrays and do a lot of operations on them. Basically, they are similar to real arrays, in the way that their index is always an integer and they have a fixed size, which in turn makes them faster to use.
i have the following code:
foreach($result->response->Results as $entry) {
echo '<tr class="'. $entry->EmailAddress.'">';
echo '<td>'. $entry->EmailAddress.'</td>';
echo '<td></td><td>';
foreach($unsubscribers->response->Results as $entry2) {
echo $entry2->EmailAddress; }
echo '</td><td></td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}
the first loop pulls in a list of recipients email address's via the campaign monitor api, the second loop pulls in the people who have unsubscribed.
My problem is, there are 100 subscribers that get pulled in, and currently 1 of them have unsubscribed. That 1 unsubscriber gets looped through 100 times, and obviously gets displayed.
How would i go about adapting the above to make it so the unsubscriber doesn't show however many times there are subscribers.
Do you mean something like this?
// Add the unsubscribers to an array
$unsubs = array();
foreach($unsubscribers->response->Results as $entry2) {
$unsubs[] = $entry2->EmailAddress;
}
// Loop through the subscribers
foreach($result->response->Results as $entry) {
echo '<tr class="'. $entry->EmailAddress.'">';
echo '<td>'. $entry->EmailAddress.'</td>';
echo '<td></td><td>';
// If the subscriber is in our unsubscriber array, output the email again
if(in_array($entry->EmailAddress, $unsubs)) {
echo $entry->EmailAddress;
}
echo '</td><td></td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}
It will only output the email in the second column if that subscriber is also in the unsubscribers array
check this codes its probably work for your way.
foreach($result->response->Results as $entry){
echo '<tr class="'. $entry->EmailAddress.'">';
echo '<td>'. $entry->EmailAddress.'</td>';
echo '</tr>';
}
foreach($unsubscribers->response->Results as $entry2){
echo '<tr class="'. $entry2->EmailAddress.'">';
echo '<td>'. $entry2->EmailAddress.'</td>';
echo '</tr>';
}
I'm trying to set variables inside a foreach() statement, but it keeps dying.
If I do this, all is fine.
foreach($array as $key => $value)
{
echo '<tr>';
echo '<td>' . $value['1'] . '</td>';
echo '</tr>';
}
But when I do this, it doesn't want to work.
foreach($array as $key => $value)
{
$mls = echo '' . $value['1'] . '';
echo '<tr>';
echo '<td>' $mls '</td>';
echo '</tr>';
}
Syntax wise, I don't see how there's a difference in these statements. I've also tried $mls = $value['1']; and that didn't want to work either.
Surely you got a syntax error complaining about the second case, right? If you say "it keeps dying", you should tell us exactly what happens when something dies. Even more, you should read the syntax error and consider what it says. The errors are descriptive so that you can figure out what's wrong.
In the second case, you aren't concatenating the strings with the . operator.
echo '<td>' $mls '</td>';
should be
echo '<td>' . $mls . '</td>';
$mls = echo '' . $value['1'] . '';
should be
$mls = $value['1'] ;
echo $mls;
and
echo '<td>' $mls '</td>'
should be
echo '<td>' . $mls . '</td>';
Your second code block should look more like this:
foreach($array as $key => $value)
{
$mls = (string) $value['1'];
echo '<tr>';
echo '<td>' , $mls , '</td>';
echo '</tr>';
}
When you type $var = echo "something" you aren't assigning any values to that variable. Instead you are outputting that string - echo has no return value.
You can typecast your variable into a string without appending and prepending empty strings.
You can use the , to echo multiple strings one after another with a little less overhead.
You should be using HTML entities for your ampersands, even though they are in an attribute's value
(Finally) You aren't actually concatenating your variable into the third echo.