Foreach loops in PHP and Joomla - php

I'm currently managing the display of MySQL content in HTML with foreach loop like this :
<?php
echo "<table class=\"tableau\">
<tr bgcolor=\"#a72333\" class=\"first\">
<th>Repere</th>
<th>Niveau</th>
<th>Enseigne</th>
<th>Activités</th>
</tr>
<tbody>";
$db= JFactory::getDBO();
$query = 'SELECT baseData, sid, fid FROM XXXX_sobipro_field_data';
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as &$value) {
if ($value->sid == 55) {
if ($value->fid == 20) {
$repere = $value->baseData;
}
if ($value->fid == 16) {
$level = $value->baseData;
}
if ($value->fid == 22) {
$title = $value->baseData;
}
if ($value->fid == 17) {
$activity = $value->baseData;
}
if ($value->fid == 21) {
$display = $value->baseData;
}
}
[...]
// It ends at if ($value->fid == 83)
}
So I name my variable like this $title_NUM, $activity_NUM, ..., where _NUM is a number starting at "nothing", it ends at 24 for now, but it could be more if I have more data in my table.
After I get the data I display the html like this :
if ($display == 1) {
echo "<tr bgcolor=\"#eaeaeb\">
<td valign=\"top\">".$repere."</td>
<td align=\"top\">".$level."</td>
<td valign=\"top\"><a data-lightbox=\"width:600;type:iframe;\" href=\"LINK\">".$title."</a></td>
<td align=\"top\">".$activity."</td>
</tr>";
}
And the same happens here I'm displaying each linke of the html "by hand" , O don't have any loop to do the job.
Is there a way to do the job with only loops ?

what i understand so far is that you have
$title1 , $title2 , $title3 , ...
you want to do loop for it
see this example
<?php
for($i=0;$i<=8;$i++)//note it start from 0 to 8
${'test'.$i}=5*$i;
$test9=5*9;
echo "let's test <br/>";
echo $test0.'<br/>';
for($i=1;$i<=9;$i++)//note it start from 1 to 9
echo ${'test'.$i}.'<br/>';
?>

Related

Getting all data after clicking a particular cell in a table

Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=65b310b4b973a7577d4953e01c09a124
Currently I have a table that displays a total count of my data values for each source. I'm getting this value after comparing 2 tables 1 is crm_leads with all my product information and 1 is crm_sources with what sources are the products related to.
Now this is the output:
Now as you can see the total count is shown under each header next to its source. There are 8 cells for each source as seen in the picture. Now these count values are inside a tags which once clicked go to viewall page.
Now here basically I want to show the data of the item that I had clicked. So for example, if I clicked the 163 under Hot status, it takes me to the viewall page and shows me id, source, enquiry_date for all those under status Hot in a table.
So basically it should detect the data for which source and which status is clicked and then accordingly make a statement like this?
select * from crm_leads where lead_source = '.$source.' and lead_status = '.$status.';
Another thing I'm thinking I can do here is put my table inside a form and pass those values as post in my controller class leadstatus which will pass that value to viewall? Not really sure on how to proceed.
Model Class:
function get_statusreport($fdate='',$tdate='')
{
$this->db->select("l.lead_status,crm_sources.title,count(*) as leadnum,l.enquiry_date,l.sub_status");
$this->db->from($this->table_name." as l");
if($fdate !='')
$this->db->where("date(l.added_date) >=",date('Y-m-d',strtotime($fdate)));
if($tdate !='')
$this->db->where("date(l.added_date) <=",date('Y-m-d',strtotime($tdate)));
$this->db->where("lead_status <>",10);
$this->db->join("crm_sources ","crm_sources.id= l.lead_source","left");
$this->db->group_by("l.lead_status,crm_sources.title");
$this->db->order_by("leadnum DESC, crm_sources.title ASC,l.lead_status ASC");
$query = $this->db->get();
$results = $query->result_array();
return $results;
}
Controller Class(leadstatus holds the view for my current table):
public function leadstatus($slug='')
{
$content='';
$content['groupedleads'] = $this->leads_model->get_statusreport($fdate,$tdate);
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/leadstatus',$content);
}
public function viewall($slug='')
{
$content='';
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/viewall',$content);
}
View class:
<?php
$ls_arr = array(1=>'Open',8=>'Hot',2=>'Closed',3=>'Transacted',4=>'Dead');
foreach($groupedleads as $grplead){
$statuses[] = $status = $ls_arr[$grplead["lead_status"]];
if($grplead["title"] == NULL || $grplead["title"] == '')
$grplead["title"] = "Unknown";
if(isset($grplead["title"]))
$titles[] = $title = $grplead["title"];
$leaddata[$status][$title] = $grplead["leadnum"];
}
if(count($titles) > 0)
$titles = array_unique($titles);
if(count($statuses) > 0)
$statuses = array_unique($statuses);
?>
<table>
<tr">
<th id="status">Source</th>
<?php
if(count($statuses) > 0)
foreach($statuses as $status){
?><th id=<?php echo $status; ?>><?php echo $status; ?></th>
<?php
}
?>
<th>Total</th>
</tr>
<?php
if(is_array($titles))
foreach($titles as $title){
?>
<tr>
<?php
$total = 0;
echo "<td>".$title."</td>";
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='".site_url('reports/viewall')."'>".$num."</a></td>";
$total += $num;
$sum[$status] += $num;
}
echo "<td>".$total."</td>";
$grandtotal += $total;
?>
</tr>
<?php } ?>
</table>
You can include the source and status in the URL like this:
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='" . site_url('reports/viewall?source=' . $source . '&status=' . $status) . "'>" . $num . "</a></td>";
$total += $num;
$sum[$status] += $num;
}
Then in your controller:
public function viewall($slug = '')
{
$content = '';
$source = $this->input->get('source');
$status = $this->input->get('status');
// Do what you want with $source and $status
$this->load->view('crm/main', $main);
$this->load->view('crm/reports/viewall', $content);
}

Php how to change background color <td> table?

I have a website and I prediction soccer. http://goaltips.nl/zeynel/Almanya2.php
I want to change background color(green) of the away wins fields if the nummer is bigger than 40 and Data is bigger than 5.
I have use this code for main page;
<?php
include 'almanya2fft.php';
include 'almanya2macsonu.php';
include 'almanya2ikibucuk.php';
foreach($array as $key => $data) {
echo "<tr>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}
?>
</table>
</div>
and for almanya2ikibucuk.php is;
foreach($array as $key => $val) {
$IkiBucukAlt=0;
$IkiBucukUst=0;
$Verisayisi=0;
$sql = "SELECT * FROM Almanya2 where B = '{$val['B']}' AND E = '{$val['E']}' AND F = '{$val['F']}' AND O ='{$val['O']}' AND A = '*' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rowcount=mysqli_num_rows($result);
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['T'] == A){
$IkiBucukAlt++;
}else{
$IkiBucukUst++;
}
}
//We use an array rather than overriding everytime
$VerisayisiData[$key]=$rowcount;
$IkiBucukAltPrediction[$key] = round(($IkiBucukAlt/$rowcount )*100);
$IkiBucukUstPrediction[$key] = round(($IkiBucukUst/$rowcount)*100);
} else {
echo " ";
}
}
$conn->close();
?>
What is the best way to do this conditions.
I hoop i was clear and someone can help me...
Thank you.
Right after you started your foreach loop get the needed color :
$color = '';
if ($AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5) {
$color = "style='background-color : green';";
}
Then add the style to each cell :
echo "<td ".$color.">".$AwayPrediction[$key]."</td>";
So when the condition is true, an inline css is applied and colors your cell else it does nothing.
You can do it with ternary operator:
foreach($array as $key => $data) {
$color = $AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5 ? 'style="background-color:green"' : '';
echo "<tr $color>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}

Append data and display html table

I have some data set. I want to arrange data like this:
My code displays result like this:
.
How can I fix this. This is my code:
<?php
echo "<tr><th></th><th>Control</th><th>Sub 1</th><th>Sub2</th></tr>";
$i=0;
$PrevIssoff=0;
$sql="SELECT `code`, `name`,`type`
FROM `testdate`
WHERE `code`='11111'
ORDER BY `code` ASC, `type` ASC ";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$frm=$row['code'];
if ($frm != $PrevIssoff && $row['type']==0)
{
$i=$i+1;
$PrevIssoff=$frm;
echo "<tr><td>$i</td><td>$row[name]</td><td></td><td></td></tr>";
}
else if($row['type']==1 )
{
echo "<tr><td></td><td></td><td>$row[name]</td><td></td></tr>";
}
else if ($row['type']==2)
{
echo "<tr><td></td><td></td><td></td><td>$row[name]</td></tr>";
}
}
echo"</table>";
?>
Database table structure - testdate
databasetable
First, your data needs to be normalized. There should be a way to write a database query to skip this step if you look hard enough.
Walkthrough each row in the while loop, building a close representation for it an array.
$dataTable = [];
while ($row = mysqli_fetch_array($result)) {
$numRows = count($dataTable);
$lastRowIndex = $numRows == 0 ? 0 : $numRows-1;
if($numRows == 0) {
$dataTable[] = [];
}
if(count($dataTable[$lastRowIndex]) == 3) {
$dataTable[] = [];
$lastRowIndex += 1;
}
$type = $row['type'];
$dataTable[$lastRowIndex][$type] = $row['name'];
}
Then make your $rowsMarkup which can be readily concatenated with the table heading.
$rowsMarkup = array_map(function($row) {
return '<tr>'.
'<td>'.$row[0] .'</td>'.
'<td>'.$row[1] .'</td>'.
'<td>'.$row[2] .'</td>'.
'</tr>';
},
$dataTable
);

Foreach Counter Broken - Lists to many of the same row

Here is the code, and this code is producing the following output: screenshot of output
the idea is to have a different header everytime the number of beds changes.
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if ($last_bed == null) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop
Solved it with an isset instead of an == null. Here is the full code for anyone else who needs something like this done:
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if (!isset($last_bed)) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop

Using php's count () command to count the result of an if statement

I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>

Categories