I'm running an events site - powered by PHP/MySQL, on Apache 2.28.
I can get the HTML table to display as per http://devzone.zend.com/article/13633.
For this site on localhost, I'm using the Twig framework mentioned at www. twig-project. org
The content is extracted from a local MySQL database:
My code:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Events</h2>
<table>
<tr class="heading">
<td>Event time</td>
<td>Event name</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.evtime|escape }}</td>
<td>{{ d.evname|escape }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
// The PHP file is below
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'MYPASS');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT * FROM myeventdb";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('countries.tmpl');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
However, I can't get the datetime to display as this for my events:
1:30pm Geography Class
Instead it displays as
13:30:00 Geography Class
Why is this, and what do I need to fix it, within the Twig syntax?
I'm fairly new to this, and I had a look through the documentation but there wasn't much on the site about it.
Cheers.
So the script is displaying 13:30:00 because that's what's coming out of the database - you're not formatting the date anywhere.
In your Twig template, you can use a date filter to format the date to your liking, according to the PHP date function formatting:
{{ d.evtime|date('g:ia')|escape }}
If you wanted to do the formatting beforehand, just use a combination of date and strtotime:
$formatted_time = date('g:ia',strtotime($unformatted_time));
Related
I have trouble with that, let me explain.
In controller, I get users.
$users = User::where('steamid','!=','')->orderBy('time','DESC')->get();
After that in Blade template I need to use PHP function for the get steam profile link from steam id.
I have a function:
function SteamName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xmla
$username = $xml->steamID;
return $username;
}
I have a foreach for every user:
#foreach($users as $user)
//so, i need to do like this;
<?php print SteamName($user->steamid) ?>
#endforeach
Put your function inside User Model
function SteamName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xmla
$username = $xml->steamID;
return $username;
}
From Your blade call the function :
#foreach($users as $user)
{{ $user->SteamName($user->steamid) }}
#endforeach
You can also try this
#foreach ($users as $user)
{{$user->steamid}}
#endforeach
I am trying to take some html from a textarea and convert it to a pdf. I donwnloaded DOMPDF from https://github.com/dompdf/dompdf and wrote the code below. When I click submit I get this error: "Internal Server Error". (my webhost doesn't tell me which line it's one)
(the name of this file is test2.php)
<?php
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<?php
if(isset($error)){
echo $error;
}
?>
<form method="post" action="test2.php">
<textarea name="content" id="content">hello world</textarea><br>
<input type="submit" name="submit" value='submit'>
</form>
</body>
</html>
I was struggled for more than one month to solve this. Finally I solved it. the solution is below.
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
?>
<html>
<head></head>
<body>
<h1>Sucess</h1>
</body>
</html>
<?php
$html = ob_get_clean();
$dompdf = new DOMPDF();
$dompdf->setPaper('A4', 'portrait');
//$dompdf->setPaper('A4', 'landscape');
$dompdf->load_html($html);
$dompdf->render();
//For view
$dompdf->stream("",array("Attachment" => false));
// for download
//$dompdf->stream("sample.pdf");
?>
I had a similar issue on a client's server when using DOMPDF for a project.
It's possible that you do not have the right level of error reporting configured with your installation of PHP.
At the top of your script place the following; error_reporting(E_ALL);
Example:
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
You should now see a more detailed message about the type of error received.
There could be issues with the HTML markup you are passing to the $dompdf->load_html($content); method or alternatively you might be experiencing memory related issues (exceeding your memory allowance).
Typically these errors will report themselves but again depending on your setup, reporting might be limited.
I created this simple Twig page on localhost on MAMP:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 0.5px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Automobiles</h2>
<table>
<tr class="heading">
<td>Vehicle</td>
<td>Model</td>
<td>Price</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.manufacturer|escape }}</td>
<td>{{ d.model|escape }}</td>
<td>{{ d.modelinfo|raw }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
and this is the code behind it:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, price FROM automobiles";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
However, I am planning to truncate the text in the modelinfo field, I believe this can be done in MySQL with the select LEFT function, but how should I modify the query?
All help is appreciated!
You can truncate text in your Twig template like this:
{{ d.modelinfo[:10] }}
That should return the first 10 characters in d.modelinfo.
Take a look at the slice filter documentation page.
Twig has a truncate filter but you have to enable the text extensions by adding the following to your config.yml file.
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
Then in your template you can use the truncate filter and pass it an integer which denotes the length of the truncation.
{{ d.modelinfo|truncate(50) }}
I am using phpmailer to send out newsletters, It seems to work out and sends out plain text emails ok, but for some reason when sending html emails drops the persons name, where as plain text works fine and shows the name.
When it sends the emails it brings this up on the result page, so it seems it isnt getting the name, but I cant see why ?.
Mail sent to: - crea#cruiseit.co.uk
Mail sent to: Toms Tackle Tom Sawyer - crea#cruiseit.co.uk
Mail sent to: - crea2k#o2.co.uk
With HTML I get : Dear , here are your {fuel} prices :
with plain text I get : Dear Bob, here are your {fuel} prices :
Does the following code look ok ?
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
require_once('./send/class.phpmailer.php');
$mailer= new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// Grab the FreakMailer class
require_once('./send/MailClass.inc');
// Grab our config settings
require_once('./send/config.php');
// Setup body
$htmlBody = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">" . $templateMessage . "</div>
</div>
</body>
</html>
';
$textBody = "$templateData->mailinglistgroupmessage";
// instantiate the class
$mailer = new FreakMailer();
// Get the user's Email
$sql = mysql_query("SELECT leadname,businessname,email,mailtype FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'");
while($row = mysql_fetch_object($sql))
{
// Send the emails in this loop.
$name = $row->leadname;
$name = $row->businessname;
$to_email = $row->email;
$mailtype = $row->mailtype;
if(!empty($row->businessname))
{
$name .= ' '.$row->leadname;
}
$to_name = $name;
if($row->MailType == 'html')
{
$mailer->Body = str_replace('{name}', $name, $htmlBody);
$mailer->IsHTML(true);
$mailer->AltBody = str_replace('{name}', $name, $textBody);
$mailer->AddAddress($to_email, $name);
}
else
{
$mailer->Body = str_replace('{name}', $name, $textBody);
$mailer->isHTML(false);
$mailer->AddAddress($to_email, $name);
}
$mailer->Send();
$mailer->ClearAddresses();
$mailer->ClearAttachments();
$mailer->IsHTML(false);
echo "Mail sent to: $name - $to_email<br />";
}
?>
Your code:
$name = $row->leadname;
$name = $row->businessname;
... which leads me to assume your variable is overwritten....
This was a small code portion, if you encounter it in more elaborate code, and you don't know where a variable is altered, you could use this little trick
class WhereIsThisAltered{
protected $value;
function __construct($value){
$this->value = $value;
}
function __toString(){
return $this->value;
}
function __destruct(){
echo "Instance with value:{$this->value} desctructed";
debug_print_backtrace();
}
}
$name = new WhereIsThisAltered($row->leadname);
You're mixing single and double quotes. Change this line:
<div id="title">" . $templateMessage . "</div>
to
<div id="title">' . $templateMessage . '</div>
I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->
The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...