I'm trying to use if-statement to change <td>-s color.
Basically, I have a simple query to retrieve information from the database.
Additionaly, I have a column there which keeps the information like if the task is accomplished or not. When I retrieve the information I get all of them, but I need the accomplished tasks to be green, and others without any color.
I've searhed for the answer, but I couldn't find anything that satisfies me.
For example:
$qry = mysql_query("select * from table");
$recs = array();
while($row = mysql_fetch_array($qry))
$recs[]=$row;
mysql_free_result($qry);
I've tried to add while statement to the code above, but I was confused and it didnt work :(
I'm printing the results using heredoc:
How to give them color here?
<?php
$last_id=0;
foreach($recs as $rec)
{
$html=<<<HTML
<tr>
<td><b>Номер</b></td>
<td>$rec[0]</td>
</tr>
<tr>
<td><b>Номер документа</b></td>
<td>$rec[1]</td>
</tr>
<tr>
<td><b>Дата регистрации</b></td>
<td>$rec[8]</td>
</tr>
<tr>
<td><b>От кого</b></td>
<td>$rec[2]</td>
</tr>
<tr>
<td><b>По</b></td>
<td>$rec[4]</td>
</tr>
<tr>
<td><b>Краткое содержание</b></td>
<td>$rec[3]</td>
</tr>
<tr>
<td><b>Исполнитель</b></td>
<td>$rec[5]</td>
</tr>
<tr>
<td><b>Срок исполнения</b></td>
<td>$rec[6]</td>
</tr>
<tr>
<td><b>Срок исполнения продлен до</b></td>
<td><b>$rec[10]</b></td>
</tr>
<tr>
<td><b>Прислан</b></td>
<td>$rec[9]</td>
</tr>
<tr>
<td><b>Примечание</b></td>
<td>$rec[7]</td>
</tr>
<tr>
<td bgcolor="#838B83"> </td>
<td bgcolor="#838B83"> </td>
</tr>
HTML;
print $html;
if($rec[0]>$last_id)
$last_id=$rec[0];
};
$new_id=$last_id+1;
?>
rather than colour use a class, so you can change it in CSS
<td<?php if($row['complete']) echo ' class="complete"'; ?>>data</td>
<table>
<tr>
<td>column heading</td>
</tr>
<?php
$qry=mysql_query("select * from table");
while($row=mysql_fetch_array($qry)) {
if($row['urcolumnn']==1)
{
echo "<tr bgcolor=green>";
}
else
{
echo "<tr>";
}
?>
<td>
<?php echo $row['urcolumn']; ?>
</td>
</tr>
<?php } ?>
</table>
This is an example code. think this will help you. here i give the background color to <tr> like this if u want to give color to <td> use this <td style="background-color:green;">
I would suggest you to use ternary operator, rather than using IF statement, or your could use another workaround to use arrays to define colors, this would help you to define various colors for each status value globally, please find an example below:
$aryColor = array(
'complete' => 'green',
'incomplete' => "red",
'pending' => 'orange'
.....
);
//you can specify values for all of your status, or leave them blank for no color, the keys in the array are the possible values from your status field
foreach($recs as $rec) {
echo '<tr bgcolor="'.$aryColor[$rec['status_field']].'">
<td>'.$rec['title_field'].'</td>
</tr>';
}
I hope this helps you out, and you can easily edit this for HEREDOC.
first you should change your column values change its structure to int and set default value as "0".so when your task is complete the field value should be change to "1".
now come to your code:
$qry = mysql_query("select * from table");
while($row = mysql_fetch_assoc($qry)){
if($row['status']==1){
echo "<td color="green">Data</td>"
}
else{
echo "<td color="white">Data</td>";
}
}
Hence you can get the rows in green which status is==1 means complete and white for incomplete.
Related
In phpMyAdmin, I am writing
SELECT `class` FROM `teachers` WHERE `var1`=3;
I can give results. The Results are 5,6,7,8,9,10.
I am Trying this code in Sublimetext3. code is like this :
<tr>
<?php
$classlistdata = $db->getrows("SELECT `class` FROM `teachers` WHERE `var1`=3; ");
foreach ($classlistdata as $ndcld) {
?>
<td height="25" colspan="3" ><span class="admin"><?php echo ($ndcld); ?></span></td>
<?php } ?>
</tr>
this code writing 6 times "array"
. How can I fix it. I am new PHP. thanks for your answer.
You should use echo $ndcld['class'];
I don't know whats behind the getrows method, but likely its just an normal SQL query since you get arrays. Well, in your case, ndcld is an array. An array containing all the queried attributes as an array key.
Change your code to:
$classlistdata = $db->getrows("SELECT `class` FROM `teachers` WHERE `var1`=3; ");
foreach ($classlistdata as $ndcld) {
?>
<td height="25" colspan="3" ><span class="admin"><?php echo $ndcld["class"]; ?></span></td>
<?php } ?>
That should do the job ;)
Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
I do not understand how to use anchor tag to pass a value. I have a form which takes a few values and submits to my mysql database. I am able to view the table. Each row has columns edit and delete. When I click edit I want to pass the primary key(job name) of that row to my edit page and similarly for delete. I am able to see the value on the URL,but I am not able to get the value on the edit page. I do not understand what is the use of ? in anchor tag.
ViewAllJobs.php
<?php
include 'jobDB.php';
$query="Select * from Jobs";
$result=mysqli_query($con,$query);
echo'
<html>
<center><h1>View all Jobs</h1></center>
<body bgcolor="#E6E6FA">
<center><form method=POST action=edit.php >
<table border="1" style="border-collapse:collapse; border-color:Black; border-style:solid; border-width:1pt">
<tr>
<th>Job Name</th>
<th>Job State</th>
<th>Schedule days</th>
<th>URL</th>
<th>Filename</th>
<th>To</th>
<th>CC</th>
<th>Reply To</th>
<th>From</th>
<th>EmailSubject</th>
<th>Email Content</th>
<th>Edit</th>
<th>Delete</th>
</tr>';
while($row=mysqli_fetch_array($result)){
echo'<tr>
<td>'.$row["jobName"].' </td>
<td>'.$row["jobState"].' </td>
<td>'.$row["jobSchedule"].' </td>
<td>'.$row["jobURL"].' </td>
<td>'.$row["jobFilename"].' </td>
<td>'.$row["jobToList"].' </td>
<td>'.$row["jobCCList"].' </td>
<td>'.$row["jobReplyTo"].' </td>
<td>'.$row["jobFrom"].' </td>
<td>'.$row["jobSubject"].' </td>
<td>'.$row["jobEmailContent"].' </td>
<td>Edit</td>
<td>Delete</td>
</tr>
';
}
echo'</table>
</form>
<center>Click to return to Home Page</center>
</center>
</body>
</html>
';
?>
edit.php
<?php
include 'jobDB.php';
$jobName=isset($_REQUEST['jobName']);
if($jobName){
echo"jobname is set";
}
else{
echo"job name is not set";
}
echo"<br>jobname is".$jobName;
$query="select* from Jobs where jobName=".$jobName;
$result=mysqli_query($con,$query);
if($result){
echo"<br>query succesful";
}
$fetch=$row=mysqli_fetch_row($result);
if($fetch){
echo"<br>result set fetched";
}
else{
echo"<br>result set not fetched";
}
?>
In edit.php $jobName=isset($_REQUEST['jobname']) gives $jobName=1 when it is supposed to have the value job1, but there does not exist a variable jobname, when I give $jobName=isset($_REQUEST['jobName']), nothing works. What is the name I should give in $_REQUEST(). Kindly help.
It should be:
$jobName = $_REQUEST['jobName'];
isset() is used to check if variable IS SET, not to assign variables.
When you use $jobName = isset($_REQUEST['jobName']);, the variable will be set to 1 as $_REQUEST['jobName'] is set and 1 represents true. Thus $jobname becomes 1.
Your code should be:
$jobName = $_REQUEST['jobName'];;
if(isset($jobName)) {
echo "jobname is set";
}
else {
echo "job name is not set";
}
echo "<br>jobname is" . $jobName;
$query = "SELECT * FROM Jobs WHERE jobName = '$jobName'";
To answer what is the use of ? in anchor tags, it is used for PHP to GET/REQUEST the values, more information at http://www.w3schools.com/php/php_forms.asp.
Hope this helps, thanks!
I want to make a horizontal bar chart in a web-page using php,mysql,javascript,css,html and 'wamp server',editor: 'Macromedia Dreamweaver',browser: 'Mozilla Firefox';
i want to read data(semister results) from table,and display data through bar chart like,
Database name exam
Table name 'sem_result' contain following columns>> regno[Primary key], uid, reg_date, exam_date, sem, result;
php code is::
<?php
// Connect to server
$cn=mysql_connect("localhost", "root", "");
//Connect to Database
mysql_select_db("exam") or die(mysql_error());
//sql query
$sql="SELECT result FROM sem_result WHERE uid=11111";
//collect results
$result=mysql_query($sql,$cn);
//read data if found
$counter=0;
while($rd=mysql_fetch_array($result))
{
$sem_result[$counter]=$rd[0]; //save sem results into array
$counter=$counter+1;
}
//display
echo "<table>
<tr>
<td>sem1</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[0]."%' height='15px'/>
</td>
<td>".$sem_result[0]."%</td>
</tr>
<tr>
<td>sem2</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[1]."%' height='15px'/>
</td>
<td>".$sem_result[1]."</td>
</tr>
</table>";
//close database
mysql_close($cn);
?>
if results are 78.95%,78.10% ,bar chart shows both result are equal, i.e 78%; image width become 78%,not 78.95% please help to fix this problem.
change table name and column name and progress.png image.
after that use it.
`
<?php $s="select count(*) as tnum from leakage";
$r=mysql_query($s) or die (mysql_error());
while($rw=mysql_fetch_array($r))
{
echo $tno=$rw['tnum'];
}
?>
<table class="table table-hover">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>No.Of Leakage</th>
</tr>
</thead>
<?php
$sql1="select dept,count(dept) as total from leakage where dept='winding'";
$result1=mysql_query($sql1) or die(mysql_error());
while($row=mysql_fetch_array($result1))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql2="select dept,count(dept) as total from leakage where dept='spining'";
$result2=mysql_query($sql2) or die(mysql_error());
while($row=mysql_fetch_array($result2))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql5="select count(dept) as total from leakage";
$result5=mysql_query($sql5) or die(mysql_error());
while($row=mysql_fetch_array($result5))
{
$tot=$row['total'];
}
?>
<tr>
<td>Total</td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo $tot;?>" height="20px"><?php echo $tot; ?></td>
</tr>
</table>
`
As #hakre already pointed out, you can't get any more precise than a single pixel or percentage, ie you can't have 78.5px or 78.5%... however, you still have some options without javascript. First, I'm not sure why you are using an image for the green bar, why not just pure html/css? Either way, here's my suggestion:
Get the total width of the bar graph, from 0 - 100, in pixels. Just by eyeballing the image you posted, I'm gonna call it 325px:
$total_width = '325';
Then, set each bar's width as such:
$bar_width = round($total_width * ($sem_result[0] / 100));
This way, a stored value of 78.10% will end up as 254px, and 78.95% will be 257px. It is still not the exact percentage, but it is closer. The longer the total width of your graph, the more precise you calculation will be.
I use mysql_fetch_array to fetch data from a mysql results set:
while($row = mysql_fetch_array($qry_result)){
Next I would like to place the data into columns in a table, but maximum of two columns at each row.
So using a table:
<table>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td colspan="2">Record Here</td>
</tr>
As you see above, I want to loop the results and create table columns in the loop.
This so that the records line up two and two on a results page.
Remember, if there is an odd number of records, then the last table column would need a colspan of 2, or perhaps just use an empty column?
Anybody know how to do this?
If I use a for loop inside the while loop, I would just be lining up the same records x times for each while loop. Confusing...
Any ideas?
Thanks
Implement a (1-indexed) counter within the while loop. Then add (after the loop):
if ($counter%2)
echo '<td></td>';
This will leave an additional blank cell in your table if the last column contains only one row.
Something like this should work...
<table>
<?php
while(true) {
$row1 = mysql_fetch_array($qry_result);
if($row1 === false) break;
$row2 = mysql_fetch_array($qry_result);
if($row2 !== false) {
echo "<tr><td>$row1</td><td>$row2</td></tr>";
} else {
echo "<tr><td coslspan=\"2\">$row1</td></tr>";
break; // output the final row and then stop looping
}
}
?>
</table>
<table>
<tr>
<?
$i=1;
$num = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result)){
if($i%2==1)
?>
<tr>
<?
?>
<td <? if($i==$num && $i%2==1)echo 'colspan="2"';?>><?=$row['keyName']?></td>
<?
if($i%2==0)
{
<?
</tr>
?>
}
$i++;
}
?>