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
);
Related
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);
}
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>";
}
Okay so I am developing a search engine for a non-profit group using MYSQL and PHP. The data appears fine from all the other fields. But when I try to get data from a drop down select box the data doesn't appear.
I know my code is pron to SQL injections however there isn't any important data kept on the server, it just info about treatments and research studies.
I would like to do it with a function. I was also wondering if there is anyway to retrieve data from multiple boxes. Like I have a keyword search and a drop down combo box both of them are set. How do I retrieve data from both columns in the database using the function I have? Thanks
Here is my code if you guys could help me that would be great thanks
The code for the html box
Broad Research Topic <select name="Treatment1">
<option value="Other">
Other
</option>
<option value="Treatment">
Treatment
</option>
<option value="PracticalCure">
Practical Cure
</option>
The php code to check if it is set
if (isset($_GET['Treatment1']) && in_array($_GET(['Treatment1']),
array('Treatment', 'PracticalCure', 'Other')) {
$state = $_GET['Treatment1'];
Investigator6($state); }
}
The Function Investigator6
function Investigator6($state)
{
$state = trim($state);
$state = preg_replace('/\s+/', ' ', $state);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $state);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($state == NULL or $state == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = ("SELECT * FROM Studies1 WHERE BroadResearchTopic LIKE
' %$keywords[$i]%'");
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($state == NULL or $state == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($state == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($state == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
b</font></b><br /></center>";
} elseif ($state == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the
database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<td style = \"padding: 10px\">" . $row['BroadResearchTopic'] . "</td>";
$row_count++;
if ($state == NULL or $state == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}
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!" ;
?>
I have a php code similar to below. I want to make just last row bold. Is it possible?
<table border = "5">
<?php
if (isset($startdate) && isset($enddate) ){
$query = "storedprocedure '$startdate','$enddate','field1'";
$result = mssql_query($query);
while ($rows = mssql_fetch_array($result) ) {
echo "<tr><td>".$rows[0]." <td>".$rows[1]."
<td>".$rows[2]." <td>".$rows[3]."
<td>".$rows[4]." <td>".$rows[5]." ";
}
}
</table>
You can use mssql_num_rows() to get the total number of rows returned by the query before you loop through them, and then (with the use of a counter), see if the current row is the last one and then apply any styling you want:
<table border = "5">
<?php
if (isset($startdate) && isset($enddate) ){
$query = "storedprocedure '$startdate','$enddate','field1'";
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
if ($numRows > 0) {
$counter = 0;
while ($rows = mssql_fetch_array($result) ) {
$style = ($counter++ == ($numRows - 1)) ? ' style="font-weight: bold;"' : '';
?>
<tr>
<td<?=$style;?>><?=$rows[0];?></td>
<td<?=$style;?>><?=$rows[1];?></td>
<td<?=$style;?>><?=$rows[2];?></td>
<td<?=$style;?>><?=$rows[3];?></td>
<td<?=$style;?>><?=$rows[4];?></td>
</tr>
<?
}
}
}
?>
</table>
I find that copying the data to an array (or better yet object) is much better, then outputting the data at the end makes these sorts of things easier.
in this case, if you drop the data into an array, you can then use lovely things like count() to see how many rows there are etc. This lets you do a simple check in the display loop to see if it is the last element in the array.
This should work:
<?php
if (isset($startdate) && isset($enddate))
{
$res=array();
$query = "storedprocedure '$startdate','$enddate','field1'";
$result = mssql_query($query);
while ($rows = mssql_fetch_array($result) )
{
$res[]=$rows;
}
}
?>
<table border = "5" id="1">
<?php
$numberRows=count(%res);
for($i=0;$i<$numberRows;$i++)
{
$boldStart="";
$boldEnd="";
if($i==($numberRows-1))
{
$boldStart="<B>";
$boldEnd="</B>";
}
echo "<tr><td>".$boldStart.$rows[$i][0].$boldEnd." </td><td>".$boldStart.$rows[$i][1].$boldEnd."
</td><td>".$boldStart.$rows[$i][2].$boldEnd." </td><td>".$boldStart.$rows[$i][3].$boldEnd."
</td><td>".$boldStart.$rows[$i][4].$boldEnd." </td><td>".$boldStart.$rows[$i][5].$boldEnd." </td>";
}
?>
</table>
Just use CSS:
t1 tr:last-child{font-weight:bold;}