I am trying to put my SQL data into an HTML data, this is the code I have so far but it does not work yet. I have tried to put HTML into my PHP code I am wondering whether I should do it the the other way round(put PHP into HTML), any reply greatly appreciated
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>";
echo"<td>" . $AE_events ['eventTitle'] . "</td>;
echo"<td>" . $AE_events ['eventDescription'] . "</td>;
echo"<td;>" . $AE_events ['eventStartDate'] . "</td>;
echo"<td>" . $AE_events ['eventEndDate'] . "</td>;
echo"<td>" . $AE_events ['eventPrice'] . "</td>;
$AE_eventTitle = $rowObj->eventTitle;
$AE_eventDescription = $rowObj->eventDescription;
$AE_eventStartDate = $rowObj->eventStartDate;
$AE_eventEndDate = $rowObj->eventEndDate;
$AE_eventPrice = $rowObj->eventPrice;
echo "<div> $AE_eventTitle<br> $AE_eventDescription<br>
$AE_eventStartDate<br>
$AE_eventEndDate<br> $AE_eventPrice<br> </div>";
}
If you want to draw a table out of data in PHP, you can have to use nested loops. The first loop manages the rows and the nested one manages the columns. Example :
$data = [
[1, 3, 5],
[2, 4, 6]
];
print "<table>";
for ($i = 0; $i < count($data); $i++) {
$row = $data[$i];
print "<tr>";
for ($k = 0; $k < count($row); $k++) {
print "<td>{$row[$k]}</td>";
}
print "</tr>";
}
print "</table>";
Outputs:
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
</table>
Related
I have this code that gets records from an API and displays it on a page. The code works and the records are displayed correctly.
$allrecords = array();
for ($i = 0; $i <= 3; $i++) {
$record = getData("https://api.site.com/v2/offers?page_size=100&page_number=" . $i);
$allrecords[] = $record['offers'];
}
$date = date('d/m/Y');
$items = $allrecords[0];
//TABLE WITH ALL THE PRODUCTS
echo "<html><head><style>td{padding:5px}th {padding: 5px;background: #035;color: #fff;}</style></head>
<body>
<br/>
<h3 class='pageDate'>" . $date . "</h3>
<table id='reportsTable' style='width:80%;margin:20px auto'><thead>
<tr id='reportRow'>
<th class='image'></th>
<th class='title'>Title</th>
<th class='small'>Price</th>
<th class='small'>CPT</th>
<th class='small'>JHB</th>
</tr>
</thead>";
foreach ($items as $key => $row) {
foreach ($row['stock'] as $val) {
foreach ($val['warehouse'] as $value) {
if ($value == 1) {
$cpt = $val['quantity_available'];
}
}
};
foreach ($row['stock'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 3) {
$jhb = $val['quantity_available'];
}
}
};
echo
"<tr>
<td class='num centerCol'><img src='placeholder.png'/></td>
<td class='productTitle'>" . $row['title'] . "</td>
<td class='small centerCol' style='text-align:center'>" . 'R' . $row['selling_price'] . "</td>
<td class='small centerCol' style='text-align:center'>" . $cpt . "</td>
<td class='small centerCol' style='text-align:center'>" . $jhb . "</td>
</tr>";
}
echo "</table></body></html>";
There are different users on the system and each has his/her own API key. I have a cron job running every night that needs to run a file that will generate a report for each user. How can I bundle this output table data and write it to html files pls? In other words I don't want to display it I want to put all this table data with the variables into a single variable that I can write to a file.
I have started writing the generate report function but am stuck at generating the html file:
function generateReports($con)
{
$query = "select username, apikey from users";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user = $row['username'];
$key = $row['apikey'];
$date = date('dm');
$filename = $user . '/' . $date . '.html';
$allrecords = array();
for ($i = 0; $i <= 3; $i++) {
$record = getData("https://seller-api.takealot.com/v2/offers?page_size=100&page_number=" . $i, $key);
$allrecords[] = $record['offers'];
}
$items = $allrecords[0];
}
}
Somehow my question is not understood This gives me an error:
$content = "
<html><head><style>td{padding:5px}th {padding: 5px;background: #035;color: #fff;}</style></head>
<body>
<br/>
<h3 class='pageDate'>" . $date . "</h3>
<table id='reportsTable' style='width:80%;margin:20px auto'><thead>
<tr id='reportRow'>
<th class='image'></th>
<th class='title'>Title</th>
<th class='small'>Price</th>
<th class='small'>CPT</th>
<th class='small'>JHB</th>
</tr>
</thead>"
foreach ($items as $key => $row) {
foreach ($row['stock_at_takealot'] as $val) {
foreach ($val['warehouse'] as $value) {
if ($value == 1) {
$cpt = $val['quantity_available'];
}
}
};
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 3) {
$jhb = $val['quantity_available'];
}
}
};
"<tr>
<td class='num centerCol'><img src='placeholder.png'/></td>
<td class='productTitle'>" . $row['title'] . "</td>
<td class='small centerCol' style='text-align:center'>" . 'R' . $row['selling_price'] . "</td>
<td class='small centerCol' style='text-align:center'>" . $cpt . "</td>
<td class='small centerCol' style='text-align:center'>" . $jhb . "</td>
</tr>;
}
</table></body></html>
";
Not an expert and the foreach statements is what I don't know how to include in the single string I want to write to a file.
What you need is something called file handling in programming. If you haven't worked with it, here is a tutorial to show you how its done. You can take your variable containing the html structure and put it in the file_put_contents(). Here is the complete documentation for file_put_contents().
By the way this is a simple example of file handling using PHP:
<?php
$file = 'path/where/you/need/file/index.html';
$content = "<h1>Hello World!</h1>";
// Write the contents in to the file
file_put_contents($file, $content);
?>
Edit:
By understanding your requirement further, I came to realise you're having trouble echo-ing the php code (i.e: foreach block). For this, you can simply do what others have mentioned in the comments, echo all the rows into that variable with complete html markup instead of printing a foreach() loop and then put that whole markup into a file. Happy coding!
To get the data into a file you first need to have all the necessary data in a string. Once you have that, you can write the string to a file.
So instead of echoing your data, just assign it to a string variable instead:
//create a string with an initial value.
$content = "
<html><head><style>td{padding:5px}th {padding: 5px;background: #035;color: #fff;}</style></head>
<body>
<br/>
<h3 class='pageDate'>" . $date . "</h3>
<table id='reportsTable' style='width:80%;margin:20px auto'><thead>
<tr id='reportRow'>
<th class='image'></th>
<th class='title'>Title</th>
<th class='small'>Price</th>
<th class='small'>CPT</th>
<th class='small'>JHB</th>
</tr>
</thead>";
foreach ($items as $key => $row) {
foreach ($row['stock_at_takealot'] as $val) {
foreach ($val['warehouse'] as $value) {
if ($value == 1) {
$cpt = $val['quantity_available'];
}
}
};
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 3) {
$jhb = $val['quantity_available'];
}
}
};
//carry on adding to the string as needed
$content .= "<tr>
<td class='num centerCol'><img src='placeholder.png'/></td>
<td class='productTitle'>" . $row['title'] . "</td>
<td class='small centerCol' style='text-align:center'>" . 'R' . $row['selling_price'] . "</td>
<td class='small centerCol' style='text-align:center'>" . $cpt . "</td>
<td class='small centerCol' style='text-align:center'>" . $jhb . "</td>
</tr>";
}
$content .= "</table></body></html>";
//now write the finished string to a file
file_put_contents("text.txt", $content);
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 know this has been asked before and I have got it working using the following code:
<?php
$maxcols = 8; $i = 0;
echo "<table id='table1'><tr>";
foreach ($id as $k => $v) {
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols) { $i = 0; echo "</tr><tr>"; }
} $i++;
while ($i <= $maxcols) {
$i++; echo "<td></td>";
}
echo "</tr></table>";
?>
This results in a table that looks like this :
I'd like to add headers to this so the end result looks like this:
I'd like to do it dynamically so if I create a table that is only 5 columns wide I'd get on the first header row ID01 - ID05 and on the second header row ID06 - ID10
I want to limit the header ID values to be no more than $maxid any extra header fields should be blank, like this : If $maxid = 12; then :
I need the header rows are made as follows and not using <TH>
<td class="mark">
I'm using some javascript to allow the movement of cell data.
The class is used to set the formatting on the header and stop items from being dragged into the fields.
Can anyone point me in the right direction on how to do this.
This should help you.
$maxcols = 8;
$maxid = 12;
$startid = 1;
echo "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td> </td>\n";
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
echo "<td>Content</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Generates
<table id='table1'>
<tr>
<td class='mark'>ID1</td>
<td class='mark'>ID2</td>
<td class='mark'>ID3</td>
<td class='mark'>ID4</td>
<td class='mark'>ID5</td>
<td class='mark'>ID6</td>
<td class='mark'>ID7</td>
<td class='mark'>ID8</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td class='mark'>ID9</td>
<td class='mark'>ID10</td>
<td class='mark'>ID11</td>
<td class='mark'>ID12</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
try this. It will work in the same way as you desired
<?php
$id= array("1","2","3","4","5","6","7","8","9","10","11","12");
$maxcols = 8; $i = 0;$j=0;$t=0;$s=0;
$maxid = count($id);
echo "<table id='table1'><tr>";
foreach ($id as $k => $v)
{
if($t == 0)
{
while ($t <= $maxcols-1) {
if($s < $maxid)
{
$s++;$t++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$t++;$s++;
}
}
echo "</tr><tr>";
}
else
{
}
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols)
{
echo "</tr><tr>";
if($j == 0)
{
while ($j <= $maxcols-1) {
if($s < $maxid)
{
$s++;$j++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$j++;$s++;
}
}
echo "</tr><tr>";
}
$i=0;
}
}
echo "</tr></table>";
?>
Output
Hi You can Use My Library:
class generate{
private $row = "<tr>{columns}</tr>";
private $td = "<td {attr}>{data}</td>";
private $attributeTR="";
private $attributeTD="";
private $tdBuilder="";
public function addCol($ColumValsArr=array("class='motota'"=>"Example")){
foreach($ColumValsArr as $key=>$val){
$newCol = str_replace("{data}",$val,$this->td);
$newCol = str_replace("{attr}",$key,$newCol);
$this->tdBuilder .= str_replace("{data}",$key,$newCol);
}
}
public function getRow(){
return str_replace("{columns}",$this->tdBuilder,$this->row);
}
}
<?php
function TableFunc($Data)
{
$Table = "<table>" . PHP_EOL;
foreach ($Data as $tags => $array) {
$Table .= "<$tags>" . PHP_EOL;
foreach ($array as $thead) {
$tag=$tags==="tbody"?"td":"th";
$Table .= "<tr>" . PHP_EOL;
if (is_array($thead)) {
foreach ($thead as $theadItem) {
if (is_array($theadItem))
$Table .= "<$tag colspan='$theadItem[1]'>$theadItem[0]</$tag>" . PHP_EOL;
else
$Table .= "<$tag>$theadItem</$tag>" . PHP_EOL;
}
}
$Table .= "</tr>" . PHP_EOL;
}
$Table .= "</$tags>" . PHP_EOL;
}
$Table .= "</table>" . PHP_EOL;
return $Table;
}
$Data = array(
"thead" => [
[["GENEL BİLGİ", 2], ["KALORİMETRE (ISINMA)", 2], ["HESAPLAMA", 2]],
["NO", "AD SOYAD", "FARK", "TUTAR", "OKUMA", "ÖDENECEK"]
],
"tbody"=>array(
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
),
"tfoot" => [["NO", "AD SOYAD", "M2", "MAHSUP", "SAYAÇ", "15°", "FARK", "TUTAR", "ORTAK ALAN", "EKSTRA", "MUAFİYET", "OKUMA", "ÖDENECEK"]]
);
echo TableFunc($Data);
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 [].
<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, '"... ';
}