<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
How do I make a pattern for the background color? For ex, grey, blue, grey blue.
There are multiple ways of doing this. Here is one.
<table>
<?php $i = 0; ?>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr<?php echo (++$i & 1 == 1) ? ' class="odd"' : '' ?>>
<td>
<?php echo $row['test'] . " " . ' ($' . $row['test2'] . ") ?><br>
</td>
</tr>
<?php endwhile; ?>
</table>
I suggest giving a CSS class (I've called it "odd" here) to every second row rather than both odd and even. Then you just do:
tr td { background: grey; }
tr.odd td { background: blue; }
in CSS.
You need something like a state variable, where you store wheter the last row was blue or grey. Then you print out the other color and update the state variable for the next pass.
This is one example:
<?php
echo '<table>';
$state = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
if( $state%2 == 0 )
echo '<td style="background-color:grey;">';
else
echo '<td style="background-color:blue;">';
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
echo '</td></tr>';
$state++;
}
echo '</table>';
?>
If it's a 2 colour pattern, use a variable to switch between blue and grey. if more than 2 colours, use a rotating counter
2 colours
$blue = true;
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td color="<?php echo $blue?'blue':'grey'; $blue ^= true; ?>">
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
More than 2 colours, the general solution:
$colourIndex = 0;
$colours = ('blue', 'red', 'green');
...
...
<td color="<?php echo $colours[$colourIndex]; $colourIndex = ($colourIndex+1)%length($colours); ?>">
You can also use the InfiniteIterator to repeat the sequence again and again. This, like the "rotating counter", works for an arbitrary amount of elements.
$props = new InfiniteIterator(
new ArrayIterator(array('a', 'b', 'c','d', 'e'))
); $props->rewind();
$l = rand(10, 20); // or whatever
for ($i=0; $i<$l; $i++) {
$p = $props->current(); $props->next();
echo 'class="', $p, '"... ';
}
Related
I have three tables created by uploaded data from the previous file. I would like to insert data in defined places, so that each service is a separate record in the table and has a separate quantity and amount assigned.
My php function:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
for ($y = 0; $y < count($net_price); ++$y) {
echo '<td>price:' . $net_price[$y] . '</td>';
for ($z = 0; $z < count($quantity); ++$z) {
echo '<td>quantity:' . $quantity[$z] . '</td>';
};
};
echo '</tr>';
}
}
And my html place:
<div class='services'>
<table>
<tr>
<th><span>NO.</span></th>
<th><span>Service name</span></th>
<th><span>Net price</span></th>
<th><span>Quantity</span></th>
</tr>
<?php listServiceName(); ?>
</table>
</div>
Now it displays to me this way, with repeated data at the end :/
broken table
That's because you are nesting your for loops. You create the <tr> and the "id" and "name" <td> for each item in service_chcecked. Then you create a "price" <td> for each service_chcecked * net_price_chcecked. And your 3rd nested loop creates a "quantity" column for each service_chcecked * net_price_chcecked * quantity_chcecked. That's why you end up with that broken table. It depends on how you receive the POST data, but if your three arrays always have the same length, you could do it all in one loop:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
echo '<td>price:' . $net_price[$x] . '</td>';
echo '<td>quantity:' . $quantity[$x] . '</td>';
echo '</tr>';
}
}
Its hard to understand whats happening but less is more and try not to mix your data & html inside your function its going to confuse you later on.
<?php
$services = $_POST['service_checked'];
$qtys = $_POST['quantity_checked'];
$prices = $_POST['net_price_checked'];
?>
<div class='services'>
<table>
<tr>
<th>NO.</th>
<th>Service name</th>
<th>Net price</th>
<th>Quantity</th>
</tr>
<? foreach($services as $k=>$service){?>
<tr>
<td><?=$k?></td>
<td><?=$service?></td>
<td><?=$qtys[$k]?></td>
<td><?=$prices[$k]?></td>
</tr>
<? }?>
</table>
</div>
I am working with an HTML webpage connected to a database and using PHP. I have in a div at the top a variable that doesn't get properly set until some PHP later in the document. Is there a way to make the div build after the later PHP, but still be where it should be at the top of the page?
Here's the code that uses the variables
<div id="HeaderRight">
<div id="HeaderRight">
<?php
echo '<a href="../Cart/index.php" class="header">
<img src="../Images/shoppingcart.gif" height="18" width="127" border="0" align="ABSMIDDLE" /> Contains '.$_SESSION["num_items"].' Items</a>'
?>
</div>
Here's the code that sets the variables
<?php
echo '<TABLE WIDTH="100%" BGCOLOR="#FFFFFF" ALIGN = "RIGHT" BORDER = "1">';
echo '<TR BGCOLOR = "818996" HEIGHT = "25"><TD>Product</TD><TD>Availability</TD> <TD>Qty</TD><TD>Price</TD><TD>Total</TD></TR>';
$strTotalPrice = 0;
for ($i=0; $i<$_SESSION['num_products']; $i++) {
$strSQL = "SELECT * FROM products WHERE ProductCode = '".$_SESSION['cart'][$i]['name']."'";
$rsProd = mysql_query($strSQL)
or die($db_name . " : " . $strSQL . " : " . mysql_error());
$rowProd = mysql_fetch_array($rsProd);
$strSQLDetails = "SELECT * FROM pagedetails WHERE Category = '".$rowProd["Category"]."'";
$rsDetails = mysql_query($strSQLDetails)
or die($db_name . " : " . $strSQLDetails . " : " . mysql_error());
$rowDetails = mysql_fetch_array($rsDetails);
// End Of "Retrieve Desired Record Set"
echo ' <TR HEIGHT = "' .$rowProd["ThumbnailHeight"]. '" ><TD style="vertical-align:middle"><img src="../'.$rowProd["Department"].'/Images/'.$rowProd["ProductCode"].'_sm.jpg" align = "left" border="0" height = "'.$rowProd["ThumbnailHeight"].'" width="100" hspace="25" />
<br><a href = "../Products/Products.php?PageID='.$rowDetails["PageID"].'" >'.$rowProd["ProductName"].'</a>
</TD>';
$strAvailability = "";
$strQuantity = 0;
if($rowProd["Stock"] < $_SESSION["cart"][$i]["qty"]){
$strAvailability = "Only " .$rowProd["Stock"]. " in Stock, Quantity Changed";
$strQuantity = $rowProd["Stock"];
$_SESSION["cart"][$i]["qty"] = $rowProd["Stock"];
}
else{
$strAvailability = "In Stock";
$strQuantity = $_SESSION["cart"][$i]["qty"];
}
echo '<TD ALIGN = "center">'.$strAvailability.'</TD>';
echo '<TD ALIGN = "center">
<input type="text" name="txtQuantity" size="2" maxlength="2" value ='.$strQuantity.'>';
echo '<form action="index.php?=?product='.$rowProd["ProductCode"].'&quantity=1" method="post">
<input type="submit" name="submit" value="Update">
</form>
</TD>';
$strPrice = $rowProd["RegPrice"] * $strQuantity;
$strTotalPrice += $strPrice;
echo '<TD ALIGN = "center">$'.$rowProd["RegPrice"].'.00</TD>';
echo '<TD ALIGN = "center">$'.$strPrice.'.00</TD></TR>';
//echo '( <a href=index.php?product=' . $_SESSION['cart'][$i]['name'] . '&quantity=1>+</a> )';
}
As Rocket Hazmat points out, it is a good idea to run all of your PHP code before rendering the HTML. Without rewriting your current code, you can achieve this with some output buffering:
<?
// add this block
function firstDiv() {
ob_start();
?>
<div id="HeaderRight">
... <? echo $_SESSION["num_items"]; ?> ...
</div>
<?
// ... and this block
$_SESSION["firstDiv"] = ob_get_contents();
ob_end_clean();
} // end of firstDiv
?>
and the same with the rest of your page
<?
function restOfYourPage() {
ob_start();
?>
<TABLE> ... <? $_SESSION["num_items"] = 666; ?> ... </TABLE>
<?
$_SESSION["restOfYourPage"] = ob_get_contents();
ob_end_clean();
} // end of restOfYourPage
?>
Then you can run the php code in reverse order, but display it in normal order:
<?
restOfYourPage();
firstDiv();
echo $_SESSION["firstDiv"];
echo $_SESSION["restOfYourPage"];
?>
This is probably something stupid I've overlooked, but could someone please tell me why the following function does not work when I'm inside the php tag.
The function sets the background colour of a table cell based on a mysql value.
Function...
<?php
/* FUNCTION DEFINES GOLD SILVER BRONZE BLACK */
function get_color($cellcolor)
{
$color = "#ffffff";
if (($cellcolor <= 100) && ($cellcolor > 85)) {
$color = "#C98910";
} else if (($cellcolor <= 85) && ($cellcolor > 70)) {
$color = "#A8A8A8";
} else if (($cellcolor <= 70) && ($cellcolor > 55)) {
$color = "#965A38";
} else if ($cellcolor <= 55) {
$color = "#000000";
}
return $color;
}
?>
My normal working usage is this...
Usage Snippet...
<?php do { ?>
<tr CLASS="data_left" >
<td bgcolor=<?php echo get_color($row_recordset1['rating']); ?>><span class="style1 count"></td>
</tr>
<?php } while ($row_recordset1 = mysql_fetch_assoc($recordset1)); ?>
</table>
My problem is this.
How should I call my function from inside a PHP tag.
I have tried the following, but all the cells came out either red, pink, or green?
And they are not just the wrong colours being assigned, they have no relation to the values contained in $row[rating].
<?php
echo '
<tr class="data_center">
<td bgcolor="get_color(' . $row['rating'] . ')">' . $row['pos'] . '</td>
</tr>';
}
?>
Try this? You need to concatenate the return of the function to the string.
<?php
echo '
<tr class="data_center">
<td bgcolor="' . get_color($row['rating']) . '">' . $row['pos'] . '</td>
</tr>';
}
?>
I'm assuming that $row['rating'] is returning a number less than or equal to 100.
Use a while() loop instead of a do{}while() loop. During the first run of the do{} statement, the variable $row_recordset1 hasn't been declared yet because the first while() condition hasn't run yet.
Additionally, try using style with CSS instead of the bgcolor attribute.
This should work:
<?php while ($row_recordset1 = mysql_fetch_assoc($recordset1)) {
$color = get_color($row_recordset1['rating']); ?>
<tr class="data_left">
<td style="background-color:<?php echo $color; ?>;"><span class="style1 count"></td>
</tr>
<?php } ?>
</table>
I have 5 pictures stored in a folder and their links stored on the database.
I want to put them in a table of three columns on each row.
<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows = $num_rows/3;
for($i=1; $i<=$rows ; $i++)
{
echo "<tr>";
for($j=1; $j<=3; $j++)
{
while($row = mysqli_fetch_array($result))
{
echo
("<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
mysqli_close($connection);
?>
</table>
</center>
</body>
</html>
The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table).
I wonder where I'm going wrong wit this code.
With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.
Here is another way to do it -
$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
if ($counter%3==1){
echo "</tr><tr>";
}
echo
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>";
// increase the counter
$counter++;
}
// close the last row
echo "</tr>";
You're looping through all the results in the first table cell.
Try something like this instead:
for($i=1; $i<=$rows ; $i++) {
echo "<tr>";
for($j=1; $j<=3; $j++) {
$row = mysqli_fetch_array($result);
if ($row) {
echo(
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
If you just want to format the display with a new row after every 3 records, you could use the modulus operator:
$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
$cntr++;
echo '
<td width="180px" height="200px">
<div class="fruit_image">
<img src="'.$row['fruit_image'].'" />
</div>
<div class="fruit_title">'.$row['fruit_name'].'</div>
</td>';
if ($cntr % 3 == 0 && $cntr != $num_rows)
echo '</tr><tr>';
}
echo '</tr>';
Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td> </td> columns.
print "<center><table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>company</td>
<td>branch</td>
<td>job title</td>
<td>contact</td>
<td>email</td>
<td>mgs</td>
</tr>";
while($row=mysql_fetch_array($query))
{
print "<tr>";
for ($i=0;$i<=(count($row)/2);$i++)
{
print "<td>$row[$i]</td>";
} print"</tr>";
}
}
else{echo " <p>No Records Found</p>";}
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
<table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<?php studentTable("Sarah", 90) ?>
I am trying to make a "stock" website for a class at school, and it's my first dive into php. Basically, the script pulls down a CSV file form a google docs spreadsheet, and (attempts) to put the values into an array for use later. I'd like to show the top 5 rising and falling stocks, but am having issues. Here's main section of the script:
<html>
<head>
<?php
#Global Variables
$rising = array();
$falling = array();
$stocks = array();
#End Global Variables
#Function to read data from the spreadsheet
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
#Process data
function populateTicker(){
$document = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtrtT_MC9_YFdHRDUGx0a2xveXNfOHJVdXJ6bVNkMFE&output=csv";
$data= get_data($document);
$lines = explode("\n", $data);
$val = "";
foreach($lines as $key => $value){
if($key != 0){
$stockInfo = explode(",", $value);
$perChange = $stockInfo[3];
$perChangeVal = "up ";
if($perChange < 0){
$perChangeVal = "down ";
$falling['$stockInfo[0]'] = $perChange;
}else{
$rising['$stockInfo[0]'] = $perChange;
}
$stocks['$stockInfo[0]'] = array("symb" => $stockInfo[0], "name" => $stockInfo[1], "price" => $stockInfo[2]);
$val = $val . "(" . $stockInfo [0] . ") " . $stockInfo [1] . " " . "\$" . $stockInfo [2] . " " . $perChangeVal . $perChange . "% today" . "\v \v \v \v | \v \v \v \v";
}
}
//asort($falling);
//arsort($rising);
return $val;
}
function getRising($index){
if($index <= count($rising)){
$keys = array_keys($rising);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
function getFalling($index){
if($index <= count($falling)){
$keys = array_keys($falling);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
?>
</head>
<body>
<DIV id='DEBUG'>
<?php
print_r($stocks);
print_r($rising);
print_r($falling);
?>
</DIV>
<center><b><u><font size="+2">Latest Prices</font><br /></u></b></center>
<DIV ID="TICKER" STYLE="border-top:2px solid #CCCCCC; border-bottom:2px solid #CCCCCC; overflow:hidden; width:100%" onmouseover="TICKER_PAUSED=true" onmouseout="TICKER_PAUSED=false">
<?php echo populateTicker(); ?>
</DIV>
<script type="text/javascript" src="webticker_lib.js" language="javascript"></script>
<div id='Top5'>
<br />
<center><b>This page does not update automatically! Please refresh the page to update the information!</b></center>
<br />
<center><b><u><font size="+2">Top 5's</font><br /></u></b></center>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Top 5 Rising</th>
<th>Top 5 Falling</th>
</tr>
<tr>
<td><?php echo getRising(1); ?></td>
<td><?php echo getFalling(1); ?></td>
</tr>
<tr>
<td><?php echo getRising(2); ?></td>
<td><?php echo getFalling(2); ?></td>
</tr> <tr>
<td><?php echo getRising(3); ?></td>
<td><?php echo getFalling(3); ?></td>
</tr> <tr>
<td><?php echo getRising(4); ?></td>
<td><?php echo getFalling(4); ?></td>
</tr> <tr>
<td><?php echo getRising(5); ?></td>
<td><?php echo getFalling(5); ?></td>
</tr>
</table>
</center>
</div>
<br />
<center><b><u><font size="+2">All Stocks</font><br /></u></b></center>
<div id='All'>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Price</th>
<th>High</th>
<th>Low</th>
<th>Percent Change</th>
</tr>
<?php
#Dynamic Table Creation
foreach($stocks as $key => $value){
echo '<tr>';
echo '<td>(' . $value['symb'] . ')</td>';
echo '<td>' . $value['name'] . '</td>';
echo '<td>' . $value['price'] . '</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>' . $vaule['perChange'] . '</td>';
echo '</tr>';
}
?>
</table>
</center>
</div>
</body>
<footer>
</footer>
</html>
But nothing gets assigned to the arrays. Any help would be appreciated.
UPDATE: I added the full source of the front page, index.php
UPDATE2: I figured it out. I come from java, and didn't fully understand how the scope of variables worked in php. A simple
<?php
global $rising, $falling, $stocks;
...
?>
did the trick
I don't know exactly about your code but I can show an example for presenting the nested arrays:
$arr = array('1' => array('1', '2'), '2');
function showNested($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
echo $value;
showNested($array);
}
else
{
echo $value;
}
}
}
UPDATE
You used $stocks['$stockInfo[0]'] in your code. I think this kind of syntax would never do anything. Totally when you use a variable in a string, you should surround it by {}. And one thing else that I never tested it before, I don't think putting an array with an index in a string would help the PHP to understand what's the current data in [].