I'm trying to echo the results of a MySQL query into the body of an email to send via PHPMailer, but am having difficulties. The query works as I successfully create the table on the page, but can't seem to get the assigning the table to a variable correct.
My Code:
$body = '<html>
<body>
<table>
<thead>
<tr>
<th>Food</th>
<th>Quantity</th>
<th>Category</th>
<tr>
</thead>
<tbody>'.
while($row = $resultOrderE->fetch(PDO::FETCH_ASSOC)){
echo '
<tr>
<td>$row['food']</td>
<td>$row['quantity']</td>
<td>$row['category']</td>
</tr>
';}.'
</tbody>
</table>
</body>
</html>';
The error I get is:
PHP Parse error: syntax error, unexpected 'while' (T_WHILE)
Any suggestions? Thanks!
you cant concate a WHILE loop to a string.
you have to loop through and ADD to the existing string per iteration of the loop
$html_string = '<html><body><table><thead><tr><th>Food</th><th>Quantity</th> <th>Category</th><tr></thead><tbody>';
while($row = $resultOrderE->fetch(PDO::FETCH_ASSOC)){
$html_string .=
'<tr><td>'.$row['food'].'</td><td>'.$row['quantity'].'</td><td>'.$row['category'].'</td></tr>';
}
// this will add the closing tags and now html_string has your built email
$html_string .= '</tbody></table></body></html>';
so the .= is the important part, it concates a string to the end of existing string
Related
I am pulling database information and displaying it in a table, the content of the title column is linked to a dynamic page. It all works perfectly but when validating my output page with the W3C Validator I get the following error and have no idea how to fix it!
Bad value newpage.php?url= DATABASE INFORMATION for attribute href on element a: Illegal character in query: not a URL code point.
It then highlights the end tag for the a href ">".
<?php
echo"<table>
<tr>
<th>Title</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</table>";
if (mysqli_num_rows($SQLresult) == 0 )
{
echo 'No results found, please try again.';
}
else
{
while ($row = mysqli_fetch_assoc($SQLresult))
{
echo "
<table>
<tr>
<td><a href='newpage.php?url=".$row['title']."'>".$row['title']."</td>
<td>".$row['A']."</td>
<td>".$row['B']."</td>
<td>".$row['C']."</td>
<td>".$row['D']."</td>
</tr>
</table>";
}
}
?>
Any help would be greatly appreciated, thanks.
Not all characters are legal in URLs. Those that are not legal can be recoded using the percent sign and two hex digits. PHP's urlencode() function does that. Use urlencode() on the part that is to be the link.
$url = urlencode($row['title']);
...
<td><a href='newpage.php?url=".$url."'>".$row['title']."</td>
Alternatively, you could do this:
<td><a href='newpage.php?url=".urlencode($row['title'])."'>".$row['title']."</td>
You can find more information about legal characters in URL/URI in RFC2396: https://www.rfc-editor.org/rfc/rfc2396#section-2
Does anyone see a problem with this HTML/PHP code? as soon as i added it, the page showed as blank, with the browser not reading any source code at all. Even if i comment it out with it still is blank!
<body>
<?php
function getInfo ($a)
{
$online = 'images/streamRing/online.png';
$offline = 'images/streamRing/offline.png';
$size = '20';
$array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($a)), true);
if ($array['stream'] != NULL)
{
$channelTitle = $array['stream']['channel']['display_name'];
$streamTitle = $array['stream']['channel']['status'];
$currentGame = $array['stream']['channel']['game'];
echo "<tr><td class='onlineStatus'><img src='$online' height='$size' width='$size' alt='Online' />Online</td>";
echo "<td>$channelTitle</td><td>$streamTitle</td></tr>";
}
else
{
echo "<tr><td class='onlineStatus'><img src='$offline' height='$size' width='$size' alt='Offline' />Offline</td>";
echo "<td>$a</td><td> </td></tr>";
}
}
?>
.... (later in the page...) ....
<table class="onlineList">
<th>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</th>
<?php
$streamer_1 = 'xxxx';
$streamer_2 = 'yyyy';
getInfo($streamer_2);
getInfo($streamer_1);
?>
</table>
The php code was developed using Kraken API, which is demonstrated rather simply here:
http://www.incendiarymedia.org/twitch/status.php
Edit: I noticed and fixed the breaking error. I used double quotes within a php echo, which is..... bad! However, the code still has an error. The table shows the headers, then the individual cells are misaligned. Somehow the images for the first column show up to the LEFT of the first column header. I don't see why!
Because this is invalid table markup
<table class="onlineList">
<th>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</th>
The <th> element behaves like a cell, but you are using it like a row instead of <tr>
Try this:
<table class="onlineList">
<tr>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</tr>
The code below is a sample code of the top oh my php web page. There are php variables being outputted in specific places.
I'd to implement an HTML to PDF converter, but it requires me to put all of my code into a single variable that the PDF converter will use in its class. How can I put my existing into into a single variable say: $html without having to open up all my PHP variables, escpaing everything and concatenating the whole place? I was thinking of using heredocsyntax but it doesn't like the <?php ?> and I'm sort of confused as I've never used it in the past. Any ideas on how to achieve this?
Ideally, this is what I'd like to do:
$html = <<<EOD
<div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
EOD;
The above doesn't capture any values outputted by $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] or by configuration::getValue(6).
Insead of:
$html = "";
$html .= "<div id=\"topHeaderView\">".configuration::getValue(6)."</div>";
$html .= "<table>";
$html .= "<tr>";
$html .= "<td>".$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]."</td>";
$html .= "</tr>";
This is something I want to avoid...
This is a good use of output buffering
ob_start();
?><div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
<?php
$html = ob_get_clean();
As far as I can see in the manual, it is not possible to call functions inside HEREDOC. A less cumbersome solution is:
$config_print = configuration::getValue(6);
$lang_print = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$config_print</div>
<table>
<tr>
<td>$lang_print</td>
</tr>
EOD;
Edit: Or you could use:
$html = <<<EOD
<div id="topHeaderView"><?= _( configuration::getValue(6) ); ?></div>
<table>
<tr>
<td><?= _( $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] ); ?></td>
</tr>
EOD;
heredoc is php syntax therefore it needs to be inside the php tags. The php documentation, here, explains the behavior of variables within heredoc strings:
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped... Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
There are also some examples in the documentation.
<?php
$value = configuration::getValue(6);
$header = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>$header</td>
</tr>
EOD;
?>
The manual has a whole chapter devoted to the assorted string syntaxes that PHP provides (4 to date). You're basically missing string interpolation:
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>{$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]}</td>
</tr>
EOD;
Fiddle
However, it isn't as simple as that. You are using PHP to generate code in another language (HTML) and you need to ensure that the resulting code is valid. Thus you cannot inject random stuff. In order to insert literal text inside HTML you need to use htmspecialchars(). And variable interpolation expects, well, variables, not functions. So the heredoc syntax offers little advantage here. Concatenation would be a simpler alternative:
$html = '<div id="topHeaderView">' . htmlspecialchars($value) . '</div>
<table>
<tr>
<td>' . htmlspecialchars($lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]) . '</td>
</tr>';
You said you don't to escape and concatenate. I understand you. That's why complex HTML generation normally relies on template engines. Find one or build your own.
i am trying to load an xml file to php in order to display a table
// load SimpleXML
$d = $_GET['d'];
$books = new SimpleXMLElement('books.xml?cat=($d)', null, true);
echo <<<EOF
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Price at Amazon.com</th>
<th>ISBN</th>
</tr>
EOF;
foreach($books as $book) // loop through our books
{
echo <<<EOF
<tr>
<td>{$book->title}</td>
<td>{$book->author}</td>
<td>{$book->publisher}</td>
<td>\${$book->amazon_price}</td>
<td>{$book['isbn']}</td>
</tr>
EOF;
}
echo '</table>';
i am unable to get the Get variable return any data.hope you can help me.
This is a single vs double quote issue.
Change
'books.xml?cat=($d)'
to
"books.xml?cat=($d)"
...and read this again. Properly.
At the very least 'books.xml?cat=($d)' is not expanded. You need to use double quotes.
I have a directory full of XML files. For each of these files I make a search at RIPE. For each search I do a couple of RegEx searches through the returned HTML code. But after a couple of loops, file_get_contents stop returning data, and all my operations after are done on an empty string.
I figured PHP may be timing out since these pages take a while to load. But wouldn't the script execution stop completely then? Instead all the loops finish and output their HTML code, though without content.
I'm also guessing there could be some sort of maximum requests pr second deal with PHP.
Could anyone here shed some light on this?
Thanks
Edit: To explain my title, a friend of mine and myself were running the script at the same time. That's why I'm guessing PHP sets a limit to how many requests it can send pr minute or something, because it seems PHP manages a varying number of loops before it stops returning data.
Edit: Added some code: (I figured it wasn't needed, due to my explanation of the problem)
<?php
set_time_limit(0);
include "pagebase.php";
$page = new pagebase();
$page->jQuery = true;
$page->formatDoc = false;
$page->addScript("javascript.js");
$page->addStylesheet("../codeclean.css");
$page->addStylesheet("stylesheet.css");
$page->title = "...";
$directory_path = "xml_documents";
$directory = scandir($directory_path);
$files = array();
foreach($directory as $string)
{
if(preg_match("/.*\.xml/", $string, $result) > 0)
array_push($files, $result[0]);
}
$content =
"
<table cellpadding=\"0\" cellspacing=\"0\">
<tr>
<td colspan=\"7\">
<center><h2>...</h2></center>
</td>
</tr>
<tr>
<td class=\"header_cell\">Case ID</td>
<td class=\"header_cell\">Description (From RIPE)</td>
<td class=\"header_cell\">IP</td>
<td class=\"header_cell\">Fil</td>
<td class=\"header_cell\">Time</td>
<td class=\"header_cell\">Type</td>
</tr>
";
foreach($files as $index => $file)
{
$xml = simplexml_load_file("$directory_path/$file");
$id = trim($xml->Case->ID);
$ip = trim($xml->Source->IP_Address);
$title = trim($xml->Content->Item->Title);
$time = trim($xml->Source->TimeStamp);
$type = trim($xml->Source->Type);
$desc_result = array();
$info_result = array();
$RIPE_result = file_get_contents("http://www.db.ripe.net/whois?searchtext=$ip");
preg_match("/(?<=descr:)(\s*)(.*)/", $RIPE_result, $desc_result);
preg_match_all("/<pre>.*<\/pre>/sm", $RIPE_result, $info_result);
$info_result[0] = implode("", $info_result[0]);
if(count($desc_result) < 1) $desc_result[0] = "<font style=\"color:red\">No description found</font>";
else $desc_result[0] = trim($desc_result[0]);
$content .=
"
<tr id=\"info_row_$index\">
<td class=\"info_cell\">$id</td>
<td class=\"info_cell\">$desc_result[0]</td>
<td class=\"info_cell\">$ip</td>
<td class=\"info_cell\">$title</td>
<td class=\"info_cell\">$time</td>
<td class=\"info_cell\">$type</td>
</tr>
<tr id=\"expanded_row_$index\">
<td class=\"expanded_cell\" colspan=\"7\">
<div id=\"content_container_$index\">
<input type=\"button\" class=\"pastey_button\" rel=\"$index\" value=\"Get info\" />
<div id=\"RIPE_$index\">$info_result[0]</div>
</div>
</td>
</tr>
";
}
$content .=
"
<tr>
<td colspan=\"6\">Vi har totalt ".count($files)." henvendelser.</td>
</tr>
</table>
";
$page->body = $content;
$page->drawPage();
?>
Testing inline code blocks
i think RIPE has usage limits - you may be being locked out if you perform too many queries in a certain amount of time.
If by timing out you mean file_get_contents timing out I'm pretty sure that'll throw an error (or at least return false). As far as I know PHP doesn't have a number of HTTP requests it can fulfil per execution.
How many items are you talking about here? Have you checked the values for those items?
You could try using set_time_limit(0) but PHP should throw an error if PHP's reaching maximum execution time so you might not need that.